Page 1 of 1

GUI functions from worker thread

Posted: Sun May 06, 2012 3:24 am
by 4ggre5510n
Greetings!

I hope you will help me this time as well :]

Why is calling GUI functions from worker thread prohibited? Is that platform dependent ( would it work under MSW )? Is there still some crash risk even with proper use of Mutexes and CriticalSections (associated with one, "to-be-modified" top level window)? Is this absolute, solid rule; something that Im absolutely not allowed to do ?

I'm asking because the only thing documentation says about this is "do not do that"...

Thanks in advance for your answers :]
Best regards

Re: GUI functions from worker thread

Posted: Sun May 06, 2012 9:52 am
by doublemax
do not do that ;)

I never considered that a serious limitation, if you think that you *need* to access gui elements from secondary threads, you usually have a program design issue.

Re: GUI functions from worker thread

Posted: Sun May 06, 2012 2:41 pm
by Radek
It depends what is meant by "accessing" exactly. At least, you need to post messages (a recommended and, IMO, the cleanest way of inter thread communication) but posting messages - that's a wx function which accesses GUI input queues. Also, examples of desirable direct accessing are gauges or static texts like "70 % complete". It is almost impossible to avoid inter thread communication in a multi threaded (GUI) app. The GUI thread would need to poll contents of shared variables constantly otherwise - a rather ugly solution.

Well, the problem consist in sharing data. You need to serialize access to any data used by more than one thread (except read-only data). You cannot change some text in your window - unless you know that no other thread just tries the same. Also, a GUI API is a complicated beast to that changing the text can cause updating other data structures somewhere. Where do you know from, that another thread does not just try to read these structures? Or update them, too? And so on.

Put every piece of wx code between wxMutexGuiEnter() and wxMutexGuiLeave() in side threads. Whenever you can, communicate by posting user-defined messages to and from side threads. Minimalize direct inter thread access to wx objects. And have a bit of luck :mrgreen:

Re: GUI functions from worker thread

Posted: Mon May 07, 2012 4:30 pm
by Auria
posting messages - that's a wx function which accesses GUI input queues
posting messages between threads is definitely possible in wx, and is NOT considered a GUI operation since event lists are thread-safe, see http://wiki.wxwidgets.org/Inter-Thread_ ... munication