#include "stdafx.h" #include <windows.h> #include <process.h> #include <iostream> #include <fstream> using namespace std; HANDLE evRead, evFinish; void ReadThread(LPVOID param) { WaitForSingleObject (evRead ,INFINITE); cout<<"Reading"<<endl; SetEvent (evFinish); } void WriteThread(LPVOID param) { cout<<"Writing"<<endl; SetEvent (evRead); } int main(int argc , char * argv[]) { evRead = CreateEvent (NULL ,FALSE ,FALSE ,NULL) ; evFinish = CreateEvent (NULL ,FALSE ,FALSE ,NULL) ; _beginthread(ReadThread , 0 , NULL) ; _beginthread(WriteThread , 0 , NULL) ; WaitForSingleObject (evFinish,INFINITE) ; cout<<"The Program is End"<<endl; return 0 ; }用互斥量代替事件实现线程间同步
时间: 2024-02-01 15:04:43 浏览: 103
好的,下面是使用互斥量代替事件实现线程间同步的代码:
```cpp
#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <iostream>
#include <fstream>
using namespace std;
HANDLE mutexRead, mutexFinish;
void ReadThread(LPVOID param) {
WaitForSingleObject(mutexRead, INFINITE);
cout << "Reading" << endl;
ReleaseMutex(mutexFinish);
}
void WriteThread(LPVOID param) {
cout << "Writing" << endl;
ReleaseMutex(mutexRead);
}
int main(int argc, char* argv[]) {
mutexRead = CreateMutex(NULL, FALSE, NULL);
mutexFinish = CreateMutex(NULL, FALSE, NULL);
ReleaseMutex(mutexRead);
_beginthread(ReadThread, 0, NULL);
_beginthread(WriteThread, 0, NULL);
WaitForSingleObject(mutexFinish, INFINITE);
cout << "The Program is End" << endl;
return 0;
}
```
这里我们使用了两个互斥量 `mutexRead` 和 `mutexFinish`,分别代替了原先的两个事件 `evRead` 和 `evFinish`。在 `main` 函数中,我们先将 `mutexRead` 解锁,这样在启动线程时,读线程可以立即运行,写线程会被阻塞。然后我们启动了读线程和写线程,并等待 `mutexFinish` 互斥量被释放,表示程序结束。在读线程中,我们等待 `mutexRead` 互斥量被释放,然后输出 "Reading",并释放 `mutexFinish` 互斥量。在写线程中,我们直接输出 "Writing",然后释放 `mutexRead` 互斥量,这样读线程就可以得到运行的机会了。
阅读全文