如何将std::thread
线程的 id 作为 id 传递到PostThreadMessage
?就像假设,我有一个线程:
// Worker Thread
auto thread_func = [](){
while(true) {
MSG msg;
if(GetMessage(&msg, NULL, 0, 0)) {
// Do appropriate stuff depending on the message
}
}
};
std::thread thread_not_main = std::thread(thread_func);
然后我想从我的主线程向上面的线程发送一条消息,以便我可以以不昂贵的方式处理消息。以免中断主线程。
喜欢:
// Main Thread
while(true) {
MSG msg;
while(GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
if(msg.message == WM_PAINT) {
PostThreadMessage(); // How do I pass the thread id into the function?
} else {
DispatchMessage(&msg);
}
}
}
问题的总结是PostThreadMessage
需要线程ID作为参数传入, 现在std::thread::get_id
没有以"DWORD
可转换格式">提供它。因此,我无法将线程的 id 作为参数传递。
我的问题是:如何将线程 id 作为参数传递给PostThreadMessage
?
可以通过调用std::thread
对象的基础"Windows 样式"线程句柄来获取其native_handle()
成员函数。由此,可以通过调用GetThreadId
WinAPI 函数并将本机句柄作为其参数传递来检索线程的 ID。
下面是一个简短的代码片段,可能是您在概述的情况下想要的:
auto tHandle = thread_not_main.native_handle(); // Gets a "HANDLE"
auto tID = GetThreadId(tHandle); // Gets a DWORD ID
if (msg.message == WM_PAINT) {
PostThreadMessage(tID, msg, wParam, lParam);
}
else {
DispatchMessage(&msg);
}
//...
std::thread
不会公开PostThreadMessage()
所需的 Win32 线程 ID。
处理此问题的最佳方法是在线程函数本身内部调用GetCurrentThreadId()
,将结果保存到变量中,然后可以在需要时与PostThreadMessage()
一起使用。
例如:
struct threadInfo
{
DWORD id;
std::condition_variable hasId;
};
auto thread_func = [](threadInfo &info){
info.id = GetCurrentThreadId();
info.hasId.notify_one();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
// Do appropriate stuff depending on the message
}
};
...
threadInfo info;
std::thread thread_not_main(thread_func, std::ref(info));
info.hasId.wait();
...
PostThreadMessage(info.id, ...);
解决方案:
可以使用native_handle()
成员函数获取线程的基础平台特定句柄,然后将其传递给PostThreadMessage()
:
std::thread thread_not_main = std::thread(thread_func);
...
PostThreadMessage(thread_not_main.native_handle(), WM_PAINT, 0, 0);