SetEvent
是 Windows API 中的一个函数,用于设置一个事件对象的状态为已触发
下面是一个使用 C++ 和 SetEvent
函数实现复杂线程控制的示例:
#include #include #include #include #include #include // 定义一个全局事件对象 HANDLE g_event = CreateEvent(NULL, FALSE, FALSE, NULL); void worker_thread(int thread_id) { std::cout << "Thread "<< thread_id << " is waiting for event..."<< std::endl; // 等待事件被触发 WaitForSingleObject(g_event, INFINITE); std::cout << "Thread "<< thread_id << " received the event!"<< std::endl; } int main() { const int num_threads = 5; std::vector threads; // 创建多个工作线程 for (int i = 0; i < num_threads; ++i) { threads.emplace_back(worker_thread, i); } // 让主线程休眠一段时间,以便其他线程有足够的时间进入等待状态 Sleep(2000); std::cout << "Main thread is setting the event..."<< std::endl; // 设置事件对象的状态为已触发 SetEvent(g_event); // 等待所有工作线程完成 for (auto& t : threads) { t.join(); } CloseHandle(g_event); return 0; }
在这个示例中,我们创建了一个全局事件对象 g_event
。然后,我们创建了多个工作线程,每个线程都会调用 worker_thread
函数。在 worker_thread
函数中,线程会调用 WaitForSingleObject
函数等待事件被触发。当主线程调用 SetEvent
函数设置事件对象的状态为已触发时,所有等待该事件的线程将被唤醒并继续执行。
请注意,这个示例仅适用于 Windows 平台。如果你需要在其他平台上实现类似的功能,可以考虑使用 C++11 标准库中的 std::condition_variable
类。