我正在使用 c++ 中的 winapi 创建一个程序。该程序涉及两个线程。我使用 CreateThread 创建线程之一。问题是 CreateThread 在创建线程之前不会阻塞。这会导致问题,因为我在线程之间发送消息,并且在创建线程之前该线程不会接收任何消息。如何解决这个问题。
最佳答案
使用CreateEvent
创建一个事件句柄,让线程A等待。在线程B中做的第一件事就是发出该事件的信号。
struct thread_data {
/* ... */
HANDLE started_event;
};
线程A:
/* We can create this on the stack. We wait for thread_B to
* copy it into its own stack before signalling the event. */
struct thread_data td;
td.started_event = CreateEvent(
NULL /* security attributes */,
FALSE /* manual reset (=NO) */,
FALSE /* initially signalled (=NO) */,
NULL /* name (=none) */ );
CreateThread(NULL, 0, thread_B, &td, 0, NULL);
WaitForSingleObject(td.started_event, INFINITE);
CloseHandle(td.started_event);
线程B:
DWORD WINAPI thread_B(LPVOID data)
{
/* local copy of thread data */
thread_data td = *((thread_data*)data);
SetEvent(td.started_event);
/* ... */
}
关于c++ - 确保线程已启动 winapi c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24513193/