I have a std::thread object and i want to send thread id which is std::thread::id to PostThreadMessageA which get a DWORD a typedef of unsigned long. How can i send thread id ?
I have a std::thread object and i want to send thread id which is std::thread::id to PostThreadMessageA which get a DWORD a typedef of unsigned long. How can i send thread id ?
Generally, you can call the function std::thread::native_handle to obtain the implementation-defined native handle type and std::thread::get_id to obtain the thread ID.
Since the function PostThreadMessage that you mentioned requires a thread ID and not a "handle", at first glance, it would appear meaningful to use the function std::thread::get_id instead of std::thread::native_handle. However, according to the official Microsoft documentation for the function std::thread::get_id, the function returns an object of type class thread::id and not a DWORD, but the function PostThreadMessage requires a DWORD for the thread ID. The official Microsoft documentation on class thread::id does not provide any documented way to convert this class to a DWORD.
Although it may be possible to convert a class thread::id to a DWORD through some kind of undocumented hack, I recommend that you use the following documented approach instead:
According to the official Microsoft documentation on the function std::thread::native_handle, the function returns a native Win32 HANDLE. This means that you can pass this HANDLE to native Win32 API functions. Therefore, you can pass such a HANDLE to the Win32 API function GetThreadId, which returns the thread ID as a DWORD. This returned value can then be passed to the function PostThreadMessage.
So, to extract the thread ID as a DWORD from an object of type std::thread, you can use the following line of code:
DWORD dwThreadId = GetThreadId( my_thread_object.native_handle() );
Please note that the function PostThreadMessage requires that the target thread has created a message queue, otherwise the function call will fail. If the thread was created through the std::thread API, it is possible that such a message queue was not created. Therefore, you should ensure that the target thread calls the function GetMessage or PeekMessage at least once before sending that thread a message using PostThreadMessage. See the official Microsoft documentation on this function for further information.