[Lazarus] TThread.WaitFor blocks the main event loop under Linux

Michael Van Canneyt michael at freepascal.org
Tue Oct 12 11:43:43 CEST 2010



On Tue, 12 Oct 2010, Graeme Geldenhuys wrote:

> On 12 October 2010 10:51, Michael Schnell <mschnell at lumino.de> wrote:
>>
>> So -> OP:
>> does it work decently in Linux ?
>
> No!  No matter where I call MyThread.WaitFor() I get a instand
> deadlock under Linux. I had to reintroduce a FPC only WaitFor method
> in a TTHread descendant, that instead uses the Finised boolean
> variable. A virtual Execute() method is also implemented that uses a
> interface object to initially set Finised to False, and then when that
> interface goes out of scope (when Execute is completed), it
> automatically sets Finished to True.  So my reintroduced WaitFor is
> implemented as follows:
>
> procedure  TMyBaseThread.WaitFor;
> begin
>  while not FFinished do CheckSynchronize(100);
> end;
>
> Unfortunately WaitFor is not virtual, so I had to use reintroduce, and
> wrapped in in IFDEF FPC because Delphi doesn't require this.
>
> I actually think my solution should be the default implementation for
> TThread.WaitFor() in FPC - this will prevent deadlocks under platforms
> other than Windows.

I am all for it, but first explain the following:

WaitFor by itself cannot cause deadlock.

There must be another call as well, I assume Synchronize(), in the thread
that you are waiting on. Is that correct  ?

Because, if it is so, then you are simply programming wrong. Your coding
style causes deadlock.

Thread 1 (main thread) says: I'll wait for thread 2;
Thread 2 says: I'll wait for thread 1 (implicitly, in sycnhronize)

Typical deadlock situation.

So, your logic contains a flaw, *IF* we take into account the current
specs of WaitFor() and Synchronize().

So what you propose is a change in specs, namely: WaitFor() is blocking
*except* in the main thread, where synchronize calls are still executed.
Main reason for this change is to avoid potential deadlocks.

Is this correct ?

Michael.




More information about the Lazarus mailing list