secondary thread accessing gui functions

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
wxJack
Experienced Solver
Experienced Solver
Posts: 83
Joined: Wed Jun 20, 2018 8:06 am

secondary thread accessing gui functions

Post by wxJack » Mon Nov 19, 2018 8:42 am

Hi !
I know that " it is strongly recommended that no secondary threads call GUI functions " .
I think it is mandatory for the writing operation, but what about the reading ones?
Can I let a secondary thread t2 access to a wxListCtrl (whose pointer is passed inside the ctr) so t2 can read some values?
thanks to all !

User avatar
T-Rex
Moderator
Moderator
Posts: 1182
Joined: Sat Oct 23, 2004 9:58 am
Location: Zaporizhzhya, Ukraine
Contact:

Re: secondary thread accessing gui functions

Post by T-Rex » Mon Nov 19, 2018 9:59 am

Since reading from wxListCtrl means also usage of GUI-related functionality, it's also not recommended because you may get into race conditions while accessing the UI control from both threads (UI and worker). If you want to send some data to the worker thread, you could probably use wxMessageQueue.
You robably could use a virtual wxListCtrl and access the `model` class for this list control from the thread directly with wxCriticalSectionLocker or wxMutexLocker (depending on your needs), but this may cause delays in your UI's responses if processing time for the data is too long.

User avatar
doublemax
Moderator
Moderator
Posts: 14082
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

Re: secondary thread accessing gui functions

Post by doublemax » Mon Nov 19, 2018 10:05 am

Warning: Enter at your own risk.

Try wrapping the code in wxMutexGuiEnter() / wxMutexGuiLeave().
https://docs.wxwidgets.org/trunk/group_ ... 8ea7ced5b5

You still need to make sure that e.g. you create a deep copy of any wxString you get from the control.

There is still no guarantee that this will work all the time. It also depends on the platform. Windows seems to be more forgiving, while GTK crashes more easily when accessing GUI elements from a secondary thread.
Use the source, Luke!

Post Reply