A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.
I've been quietly beavering away on code and decided to stop and make sure that what I'm doing sounds sane. I have a GUI app that talks to a server. The method I decided to use was a message passing system like this:
Now, for a simple request for listbox data update I have pretty much all of this already working, however, it just occurred to be that GUI's generally run out of a separate thread and hence the ListBox above could be acted upon by two threads at the same time. Simple answer of course is to use a Mutex, but, I'm wondering if I'm engineering this whole thing the wrong way?
Usually your GUI toolkit has a method to invoke some method on the GUI thread. You would use that from your client worker thread after getting the response back from the server. In C#, for example, every Control has an Invoke(Delegate) method.
I hope that helps. If not, what is your development platform?
Monday, April 23, 2007
In Windows, you can put user messages (WM_USER + ???) into a GUI's message loop without needing to lock the GUI (or the message loop).
Monday, April 23, 2007
Don't use WM_USER, use WM_APP instead.
If you want to avoid crashes, always update the GUI from the main thread. Use your alternate threads to collect the data but they should pass messages back to the main thread which should be responsible for managing any GUI updates.
Tuesday, April 24, 2007
With threads keep it simple - mutex etc. are very easy to get wrong and unless you are very careful at least one customer's machine will manage to hang or crash continually.
Use PostMessage as described by some others above from your worker threads to send any info. to your GUI thread. This will guarantee no deadlocks.
You can do this using WM_APP + some custom number.
All you then have to do is ensure your code can cope with messages from different threads interleaving with each other.
If you need your GUI to signal your worker thread consider using events - see CreateEvent.
Thanks guys. Thats a much better model than what I would have put together.
Friday, April 27, 2007
In the context of Windows platform:
1. Never implement UI in multiple threads. You will avoid lots of troubles by including all your UI work in the main thread of the application.
2. Use PostMessage() to update the UI from the worker thread. This allows you to avoid deadlocks across threads.
3. If you are following the above, you should be fine with synchronization part. The updates of the UI is protected automatically by the message pump of the main thread. No extra work needs to be done on your side.
4. You still need to protect shared data between worker threads.
Hope this helps.
This topic is archived. No further replies will be accepted.Other recent topics
Powered by FogBugz