簡體   English   中英

如何在 PostThreadMessage 中將 std::thread 作為線程 ID 傳遞?

[英]How to pass std::thread as thread id in PostThreadMessage?

如何將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

您可以通過調用其native_handle()成員 function來獲取std::thread object 的底層“Windows 樣式”線程句柄。 從那里,您可以通過調用GetThreadId WinAPI function並將該本機句柄作為其參數傳遞來檢索線程的 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。

處理此問題的最佳方法是在線程 function 本身內部調用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()成員 function 來獲取線程的底層平台特定句柄,然后將其傳遞給PostThreadMessage()

std::thread thread_not_main = std::thread(thread_func);

...

PostThreadMessage(thread_not_main.native_handle(), WM_PAINT, 0, 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM