[fpc-pascal] PostMessage() from a thread (in a thread save manner)
Lukas Gradl
fpc at ssn.at
Mon Oct 20 18:43:49 CEST 2008
Graeme Geldenhuys schrieb:
> Some developers prefer to pass in a GUI component to a thread
> instance, so the thread knows what widget to update. Other users
> prefer to post a "gui update" message to the application event queue.
>
> I'm very new to threads and might know just enough to make in
> dangerous. :-) In fpGUI the application's "custom" event queue is a
> linked-list structure. If threads post messages to that queue, I
> obviously need to make the queue manipulation code thread safe.
>
> fpgApplication is a global singleton of the TfpgApplication class.
> fpgPostMessage() is a stand-alone function (not a member of
> TfpgApplication class). To make fpgPostMessage() thread save, I
> instantiated a TCriticalSection instance in the TfpgApplication class
> - in the constructor. I added two member functions .Lock and .Unlock
> which calls FCritSect.Enter and FCritSect.Leave respectively. In
> fpgPostMessage, I call fpgApplication.Lock, then manipulate the
> message queue and then call fpgApplication.Unlock.
>
> Is this the correct way to make my event queue thread save?
It is - theoretically. I use threads quite a lot and found it a constant
source of problems, to create a deadlock here and there when using the
messagequeue or to forget some lock/unlock somewhere. (you will need
more than PostMessage for your queue! *bg*)
I prefer to implement the messaging in the object it belongs to - in
this case on fpgApplication. The Queue will not be visible from outside,
only funcions like PostMessage, GetMessage or DiscardMessage. This way
you can make shure, the lock/unlock sequence will be used correctly...
Regards
Lukas
(Just seen that Vincent was a bit faster than me, but with quite the
same thougts...)
--
--------------------------
software security networks
Lukas Gradl <fpc#ssn.at>
Eduard-Bodem-Gasse 9
A - 6020 Innsbruck
Tel: +43-512-214040-0
Fax: +43-512-214040-21
--------------------------
More information about the fpc-pascal
mailing list