帮我改写一下程序,用事件代替互斥量实现线程间的同步
时间: 2023-12-10 21:39:33 浏览: 28
好的,以下是用事件代替互斥量实现线程间的同步的程序:
```c++
#include <iostream>
#include <thread>
#include <chrono>
#include <windows.h>
using namespace std;
HANDLE event;
void thread_func(int id) {
cout << "Thread " << id << " starts." << endl;
WaitForSingleObject(event, INFINITE);
cout << "Thread " << id << " is running." << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "Thread " << id << " finishes." << endl;
}
int main() {
const int num_threads = 3;
thread threads[num_threads];
event = CreateEvent(NULL, TRUE, FALSE, NULL);
for (int i = 0; i < num_threads; ++i) {
threads[i] = thread(thread_func, i);
}
cout << "Press ENTER to start the threads." << endl;
cin.get();
SetEvent(event);
for (int i = 0; i < num_threads; ++i) {
threads[i].join();
}
CloseHandle(event);
return 0;
}
```
在这个程序中,我们使用了Windows API中的事件来实现线程间的同步。在主线程中创建了一个事件对象,并将其标志设置为未触发。然后,在每个子线程中,我们调用了WaitForSingleObject函数来等待事件被触发。当主线程调用SetEvent函数时,事件被触发,所有子线程开始执行。最后,我们在主线程中等待所有子线程执行完毕,并关闭事件对象。