Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

Is TCriticalSection enough?

Avatar of aureliuh
aureliuh asked on
Editors IDEs
11 Comments1 Solution653 ViewsLast Modified:
Hello Experts,

I need to protect a buffer (AnsiString object) from being corrupted by simultaneous access to its structure. It is accessed in two ways:

1. on reading from socket -> append to buffer

2. private method called periodically ->search for separator, extract the first part from the buffer by given separator, removing it from the buffer.

I'm noticing the buffer gets corrupted occasionally and I have an idea why. Seems the socket will write into the buffer while is being sliced or vice versa...

The entire logic described above happens inside a single thread (TMyThread). This class contains the socket to read from, the buffer, the critical section and also emulates a timer object by doing the following:

          if(MilliSecondsBetween(Now(), lastTimerFired) > 2000)
                lastTimerFired = Now();



The TimerLogic() is the method consuming the buffer in the manner I have already described. Although each access to my buffer is protected by Acquire() / Release() don't think it's enough though, as my program crashes rather frequently. The socket OnRead event gets executed in the same thread so I guess TCriticalSection will not help me in this case. I have read that it helps when multiple threading, but not when the happens in the same thread.

What options do I have to solve this problem?

I guess there is the boolean flag option to protect against simultaneous access to the buffer, but I'm not sure this is safe enough...

Thank you,
Avatar of kode99

Our community of experts have been thoroughly vetted for their expertise and industry experience.

This problem has been solved!
Unlock 1 Answer and 11 Comments.
See Answers