C++从主线程调用方法

dar*_*eir 1 c++ user-interface multithreading synchronization

在我的一个类中,我使用以下方法启动一个线程:

HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &myThread, NULL, 0, &threadID );
Run Code Online (Sandbox Code Playgroud)

从这个线程我想调用一个必须从主线程调用的方法(该方法与UI交互)但我真的不知道如何做,因为主线程不能等到" myThread"通知它.

我见过很多

while(true){
  //wait something from myThread
}
Run Code Online (Sandbox Code Playgroud)

但我不能这样等!

有任何想法吗?

小智 5

由于您的主线程是UI,因此您可以向其发送消息.

#define WM_USER_EXECUTE_MY_CODE (WM_USER + 1000)
Run Code Online (Sandbox Code Playgroud)

您的UI消息循环应该处理消息:

// API code
// LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
// create message map yourself if you're using MFC

if (iMsg == WM_USER_EXECUTE_MY_CODE)
{
    // execute your code must run in main thread
}
Run Code Online (Sandbox Code Playgroud)

在您的工作线程中,向UI发送消息

// HWND hwnd = handle to main UI window
// if you need some parameters, send them through WPARAM or LPARAM
SendMessage(hwnd, WM_USER_EXECUTE_MY_CODE, 0, 0);  
Run Code Online (Sandbox Code Playgroud)