I have an operation that takes several seconds which is blocking my main thread, which freezes my UI. So, I need to put the operation on a separate thread.
Below mimics what I'm trying to do though obviously doesn't work because join()
blocks until the thread finishes.
What's the correct approach for allowing the main thread to continue to handle UI events while the button-press thread works on its operation? (C++17, Windows 10, WxWidgets)
void OnButtonPress()
{
std::thread t1 = std::thread( []
{
std::this_thread::sleep_for( std::chrono::milliseconds(5000) );
} );
t1.join();
}
The simplest way to use threads from a GUI application is to launch the thread and return to the main loop immediately, then post an event when the thread is about to terminate. The handler for this event can join the thread, and you also need to remember to do it on shutdown if the application is closed before the thread has time to terminate.
It is also usually better to keep a background worker thread (or several) running all the time, rather than launching it at button press and communicate with it using messages (wxMessageQueue is a simple class which can be useful for this) telling it what should be done.