如何处理 std::thread 中的 PostMessageThread 消息?

Amr*_*eev 3 c++ winapi multithreading stdthread

在我的主线程中的某个地方我正在调用PostThreadMessage(). 但我不知道如何在std::thread我已发送到的地方处理它。

我试图std::thread这样处理它:

while(true) {
    if(GetMessage(&msg, NULL, 0, 0)) {
        // Doing appropriate stuff after receiving the message.
    }
}
Run Code Online (Sandbox Code Playgroud)

我从主线程发送消息,如下所示:

PostThreadMessage(thread.native_handle(), WM_CUSTOM_MESSAGE, 0, 0);
Run Code Online (Sandbox Code Playgroud)

我不知道我是否应该像在线程中那样收到该消息。

我想知道的是,如何检查“工作线程”是否正在接收我发送的消息。

Rem*_*eau 6

返回的内容std::thread::native_handle()实现定义的(根据C++ 标准中的[thread.req.native] )。甚至不能保证它会返回所需的线程 IDPostThreadMessage()

例如,MSVC 的实现内部std::thread使用,其中返回 Win32 。您必须使用该句柄来获取线程 ID。CreateThread()native_handle()HANDLEGetThreadId()

的其他实现可能根本std::thread不使用。CreateThread()例如,他们可以改用该pthreads库,该库native_handle()将返回一个pthread_t与 Win32 API 不兼容的句柄。

解决这个问题的一个更安全的方法是native_handle()根本不使用。在线程函数本身内部调用GetCurrentThreadId(),将结果保存到一个变量中,然后您可以在需要时使用该变量PostThreadMessage(),例如:

struct threadInfo
{
    DWORD id;
    std::condition_variable hasId;
};

void threadFunc(threadInfo &info)
{
    info.id = GetCurrentThreadId();
    info.hasId.notify_one();

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        // Doing appropriate stuff after receiving the message.
    }
}

...

threadInfo info;
std::thread t(threadFunc, std::ref(info));
info.hasId.wait();
...
PostThreadMessage(info.id, WM_CUSTOM_MESSAGE, 0, 0);
Run Code Online (Sandbox Code Playgroud)