Multi-threaded GUI

KlausO oberhofer at users.sf.net
Fri Jul 27 02:15:37 PDT 2012


Am 26.07.2012 19:15, schrieb Simon:
> On 26/07/2012 09:16, Russel Winder wrote:
>> On Wed, 2012-07-25 at 23:17 +0200, Kagamin wrote:
>>> On Wednesday, 25 July 2012 at 18:50:51 UTC, Simon wrote:
>>>> You have to be very, very careful with trying to do multi
>>>> threading w/ windoze windows. Try doing a google search on it,
>>>> and the advice is invariably: don't do multi threaded windows.
>>>> Everybody including people famous for their in-depth window
>>>> knowledge recommends a single thread UI with non-UI worker
>>>> threads.
>>>
>> So if Windows is really doing multi-threaded widget management, this
>> would be very interesting.  Where is the material that I can look at
>> that leads you to say that Windows is a multi-threaded UI.
>
> On 'doze every thread can have it's own message pump and therefore it's
> own UI, but if you have an ancestor/descent relation between 2 windows
> they must belong to the same thread.
>
> Otherwise you are pretty much guaranteed a deadlock, unless you only
> ever use MsgWaitForMultipleObjectsEx to synchronise. But that's kinda of
> unachievable unless you have written every single line of code yourself.
>
> So you can have threads with separate UIs as long as you don't make the
> windows of one thread the child of another.
>

Every thread that creates a window will get a message queue created and 
assigned (It's then called a GUI thread).
Under normal circumstances your thread will enter an event loop where 
you call the GetMessage/DispatchMessage function pair. GetMessage gets 
only messages from the threads message queue and DispatchMessage 
dispatches only to the windows owned by the thread.

You can get into troubles when you send a message via SendMessage from 
thread A to a window owned by thread B and the event loop of thread B 
does not handle this message (e.g. by having a modal dialog opened in 
thread B). In this case thread A is blocked until the message is 
processed by B's event loop.

SendMessage is often used in code dealing with Parent/Child window 
relations, so the warning above is justified. But as long as your child 
window event loop is not blocked (or some other access to a shared 
resource creates a deadlock) it works.

There is a technical article about multithreaded GUI and Win32 on MSDN. See
http://msdn.microsoft.com/en-us/library/ms810439.aspx


More information about the Digitalmars-d mailing list