c++ - 确保线程已启动 winapi c++

标签 c++ multithreading winapi

我正在使用 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/

相关文章:

c++ - 具有透明缓冲区的 DirectX11 ClearRenderTargetViewback?

c++ - 线程间通信。如何向另一个线程发送信号

c# - 在 C# 中如何将 IP 地址字符串解析为 uint 值?

c++ - 使用指针写入数组元素的问题

C++调用公共(public)基类的私有(private)/ protected 函数

c# - 在 C# 中使用 BackgroundWorker 的线程问题

java - 捕捉到 "InterruptedException"后,为什么 "Thread.currentThread().isInterrupted()"的值为 false?

delphi - 如何从窗口句柄中获取可执行文件名?

windows - 如何创建对话框以在 Fortran 中收集用户输入

c++ - C++中的继承问题