C++ 从主线程调用方法

标签 c++ multithreading user-interface synchronization

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

HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &myThread, NULL, 0, &threadID );

我想从这个线程调用一个必须从主线程调用的方法(该方法正在与 UI 交互)但我真的不知道该怎么做,因为主线程不能等到“myThread”通知它。

我看过很多

while(true){
  //wait something from myThread
}

但我等不及了!

有什么想法吗?

最佳答案

因为您的主线程是 UI,您可以向它发送消息。

#define WM_USER_EXECUTE_MY_CODE (WM_USER + 1000)

您的 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
}

然后在您的工作线程中,向 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);  

关于C++ 从主线程调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11366408/

相关文章:

c - 添加到 HIMageList 失败,无法找出原因

c++ - 在 C++ 中将 int 设置为 Infinity

c++ - 线程安全队列C++

multithreading - 多线程程序中的QPointer

java - 使用 Swing 设计聊天布局

java - 阻止除一个组件之外的整个 swing ui - "dialog style"

c++ boost map程序在删除后崩溃

c++ - 我的文件输出到屏幕两次 C++?

c++ - C++中重载运算符的引用

python 2 定时器不遵循顺序