简体   繁体   English

在多线程环境中对代码进行排序

[英]Sequencing code in a multithreaded environment

I have a multithreaded C++ MFC application. 我有一个多线程C ++ MFC应用程序。 I have one worker thread to execute my program logic, and the main thread is dedicated to handling GUI events. 我有一个工作线程来执行程序逻辑,而主线程专用于处理GUI事件。 The GUI thread spawns the program logic threads, and detaches execution from it, like this - GUI线程产生程序逻辑线程,并从其分离执行,如下所示-

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

My program logic takes roughly 5 minutes to execute. 我的程序逻辑大约需要5分钟才能执行。

Here is my problem : I want to call a function in the main GUI thread after my program logic has finished execution. 这是我的问题:我想在程序逻辑完成执行后在主GUI线程中调用一个函数。 How do I signal my main thread from the programLogic thread as it nears the end of execution? 在接近执行结束时,如何从programLogic线程发出我的主线程信号?

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. PS分离我的programLogic线程的原因是为了不冻结我的主线程,因此它可以响应GUI事件。

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: 您可以使用C ++ 11 async解决方案并使用wait_for轮询结果,但是在您的特定情况下(在Windows环境中),我将寻求更好的解决方案:

1) Define a custom WM_ message and map it for handling, eg 1)定义一个自定义WM_消息并将其映射以进行处理,例如

 #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 2)当您的逻辑线程结束到主窗口时, 发布WM_MYMSG

3) Handle the logic's termination in ThreadHasFinished 3)在ThreadHasFinished处理逻辑的终止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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