[fpc-devel] Multithreading wait for

Vinzent Höfler JeLlyFish.software at gmx.net
Wed Dec 3 20:57:06 CET 2008

Mattias Gaertner wrote:
> On Wed, 03 Dec 2008 19:41:12 +0100
> Vinzent Höfler <JeLlyFish.software at gmx.net> wrote:
> If I understand RTLEventWaitFor correct, then it waits until another
> thread calls RTLeventSetEvent.

Unless it's already signalled, then it should run right through.

> So I must check *before* calling RTLEventWaitFor, that some other thread
> is running, must I not?

No, assuming RTLEvent implements a persistent signal, not a transient 
one. I am not 100% sure here (so someone should check the source), but I 
remember that there were two versions (mimicking the Windows-Events), 
depending on how one would set them up. I implemented my own versions 
some time ago (fpc2.0.0), but that was due to some bugs and quirks in 
fpc's implementation, so I'm not really up to date if those are fixed 
now for all platforms.

>>> The problem is the gap between LeaveCriticalSection and
>>> RTLeventWaitFor. During this time the other threads may finish. So
>>> there is no one left to wake up the waiting thread.
>> So your asking the wrong question. You don't want an efficient wait 
>> loop, you want a wait loop free from race conditions.
> :)
> I know how to do a race condition free loop inefficiently using a spin
> lock. My question is, if it can be done race condition free and
> efficiently, to allow switching thousands of times a second without busy waiting.

That's what it should do (although the term "efficiently" may depend on 
some other factors like number of processing units, threads waiting, 
average wait time and such).

>> Well, depending on what your checks do, you may not even need the 
>> critical section if you reverse the logic. Either all checked threads 
>> are finished or they aren't. If the state changed during the check,
>> the check code will be invoked immediately, because the event will
>> already be signalled again.
> The critical section is needed, because after a thread finished some
> work it starts some other work.

Well, in that case... Another solution would be to provide specific 
events for the waiting threads, but this requires quite some more amount 
of administrative work, so in the end it may even turn out to be less 
efficient. ;)


More information about the fpc-devel mailing list