[Lazarus] Lazarus application crash. Is PostMessage thread safe?

Giuliano Colla giuliano.colla at fastwebnet.it
Sat Feb 13 12:27:42 CET 2016


Il 12/02/2016 15:35, Michael Schnell ha scritto:
> On 02/12/2016 03:17 PM, Mattias Gaertner wrote:
>> IMHO, Michael, you should not redefine words. It confuses people. 
>> Reentrant means it can be called again, while it is still running. It 
>> does not need to be thread-safe. 
>
> Sorry that was not me. The subject here is ".... thread save ...." ,so 
> I tried to explain exactly the difference you mention.
>

It was possibly me causing the confusion.

I was experiencing random crashes triggered from a PostMessage executed 
in a different thread.

My first assumption was that possibly PostMessage wasn't thread safe, 
and this is the reason of the subject of my first post.

Further analysis has shown that this was not the case. It was not a 
matter of thread-safe, but a matter of recursion.

At least under Qt widgetset, it may happen that calling 
Application.ProcessMessages from within a Message Handler will cause the 
same message which was being processed to be processed again, the 
handler called again and Application.ProcessMessages being called again, 
thus originating an endless loop and a consequent stack overflow.

All of that apparently originates in the g_main_context_iteration() 
procedure of Glib2, which, in some cases, doesn't properly terminate a 
dispatch operation, and in case of recursion will execute again a 
g_main_context_dispatch() for a message already dispatched. As it is 
g_main_context_iteration() responsibility to decide which procedures to 
call and when terminate, it is its responsibility to provide appropriate 
protection from recursion.

Looking into the code of gmain.c of Glib2, and in different versions, it 
can be seen that attempts have been made to avoid the problem, but 
apparently there's still a hole left.

The result is to make Application.ProcessMessage not 100% reentrant, 
because of a Glib2 bug.

Giuliano





More information about the Lazarus mailing list