#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-04-29 15:19:54 浏览: 111
基于VC中使用ForceInclude来强制包含stdafx.h的解决方法
以下是使用信号量代替事件实现线程间同步的代码:
#include <windows.h>
#include <process.h>
#include <iostream>
#include <fstream>
using namespace std;
HANDLE hSemaphore;
int counter = 0;
void ReadThread(LPVOID param) {
WaitForSingleObject(hSemaphore, INFINITE);
cout << "Reading" << endl;
ReleaseSemaphore(hSemaphore, 1, NULL);
}
void WriteThread(LPVOID param) {
WaitForSingleObject(hSemaphore, INFINITE);
cout << "Writing" << endl;
ReleaseSemaphore(hSemaphore, 1, NULL);
}
int main(int argc, char* argv[]) {
hSemaphore = CreateSemaphore(NULL, 1, 1, NULL);
_beginthread(ReadThread, 0, NULL);
_beginthread(WriteThread, 0, NULL);
WaitForSingleObject(hSemaphore, INFINITE);
cout << "The Program is End" << endl;
ReleaseSemaphore(hSemaphore, 1, NULL);
CloseHandle(hSemaphore);
return 0;
}
在这个示例中,我们使用了一个计数器和一个信号量来进行线程间同步。计数器的初始值为1,信号量的初始值也为1。在每个线程中,我们先等待信号量(相当于等待事件),然后进行操作,最后释放信号量(相当于设置事件)。在主线程中,我们先等待信号量,然后输出程序结束的信息,最后释放信号量。这样就保证了两个线程的顺序执行。
阅读全文