简体   繁体   中英

Sequencing code in a multithreaded environment

I have a multithreaded C++ MFC application. I have one worker thread to execute my program logic, and the main thread is dedicated to handling GUI events. The GUI thread spawns the program logic threads, and detaches execution from it, like this -

void CMyDocument::InGUIThread()
{
    std::thread tProgramLogic(programLogicThreadFunction);
    tProgramLogic.detach()
}

My program logic takes roughly 5 minutes to execute.

Here is my problem : I want to call a function in the main GUI thread after my program logic has finished execution. How do I signal my main thread from the programLogic thread as it nears the end of execution?

PS The reason I detach my programLogic thread is so that I dont freeze my main thread, and thus it is responsive to GUI events.

You could go for a C++11 async solution and poll the result with wait_for , but in your specific case (in a Windows environment) I'd go for an even better solution:

1) Define a custom WM_ message and map it for handling, eg

 #define WM_MYMSG (WM_USER + 42)
 BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
     ON_MESSAGE(WM_MYMSG, ThreadHasFinished)
 END_MESSAGE_MAP()

2) Post WM_MYMSG when your logic thread ends to the main window with

3) Handle the logic's termination in ThreadHasFinished

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM