Re: Semaphores in Delphi



Locke wrote:
I'm trying to implement a simple semaphore to protect critical sections of code with the following procedures.

Then why don't you just use a critical section or a semaphore? Why invent your own?

Read about EnterCriticalSection and CreateSemaphore.

Question is are these safe, or is it possible that 2 threads could slip through EnterCritical at the same time?

Yes, it's possible for two threads to pass through at the same time, for loose enough definitions of "same." Heck, it's possible for 50 threads to pass through.

procedure EnterCritical;
begin
while semaphore do sleep(30);
semaphore:=true;
end;

Imagine that the variable starts out False. Thread X and thread Y both call EnterCritical at the same time. They both check and discover that semaphore is False. They both continue to the next line and set semaphore to True. Bang.

Now imagine semaphore is True, as set by thread Z. Thread X and thread Y both call EnterCritical and find semaphore is True. They both call Sleep, and during that time thread Z calls ExitCritical to set semaphore to False. X and Y awaken and we're back to previous case. Bang.

procedure ExitCritical;
begin
semaphore:=false;
end;


--
Rob
.