操作系统实验课所写的代码:
#include <windows.h>
#include <iostream.h>DWORD WINAPI write1(
LPVOID lpParameter // thread data
);
DWORD WINAPI write2(
LPVOID lpParameter // thread data
);
DWORD WINAPI read1(
LPVOID lpParameter // thread data
);
DWORD WINAPI read2(
LPVOID lpParameter // thread data
);
int flag = 0;
HANDLE hMutex=CreateMutex(NULL,FALSE,NULL);;
void main()
{
while(true)
{
HANDLE ThWr1=CreateThread(NULL,0,write1,NULL,0,NULL);
HANDLE ThWr2=CreateThread(NULL,0,write2,NULL,0,NULL);
HANDLE ThRe1=CreateThread(NULL,0,read1,NULL,0,NULL);
HANDLE ThRe2=CreateThread(NULL,0,read2,NULL,0,NULL);
CloseHandle(ThWr1);
CloseHandle(ThWr2);
CloseHandle(ThRe1);
CloseHandle(ThRe2);
if(hMutex)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only instance can run!"<<endl;
return;
}
}
Sleep(5500); //交出cpu的使用权
}
}
DWORD WINAPI write1(
LPVOID lpParameter // thread data
)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"write1 is writing"<<endl;
cout<<"Only write1 can running"<<endl;
Sleep(10); //交出cpu的使用权
cout<<"write1 dead"<<endl;
ReleaseMutex(hMutex);
return 0;
}
DWORD WINAPI write2(
LPVOID lpParameter // thread data
)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"write2 is writing"<<endl;
cout<<"Only write2 can running"<<endl;
Sleep(10); //交出cpu的使用权
cout<<"wirte2 dead"<<endl;
ReleaseMutex(hMutex);
return 0;
}
DWORD WINAPI read1(
LPVOID lpParameter // thread data
)
{
Sleep(98);
if(flag >0)
cout<<"read1 is reading"<<endl;
// cout<<"yes"<<endl;
WaitForSingleObject(hMutex,INFINITE);
flag++;
cout<<"read1 is reading"<<endl;
cout<<"reading also can read,but writing can't"<<endl;
Sleep(10); //交出cpu的使用权
ReleaseMutex(hMutex);
cout<<"read1 dead "<<endl;
flag--;
return 0;
}
DWORD WINAPI read2(
LPVOID lpParameter // thread data
)
{
Sleep(98);
if(flag >0)
cout<<"read2 is reading"<<endl;
// cout<<"yes"<<endl;
WaitForSingleObject(hMutex,INFINITE);
flag++;
cout<<"read2 is reading"<<endl;
Sleep(10); //交出cpu的使用权
ReleaseMutex(hMutex);
cout<<"read2 dead"<<endl;
flag--;
return 0;
}
本文展示了一个使用Windows API中的互斥锁(Mutex)来实现线程同步的例子。具体包括四个线程函数:两个写操作线程(write1和write2)及两个读操作线程(read1和read2)。通过互斥锁确保了写操作不会同时进行,并允许多个读操作并发执行。
2196

被折叠的 条评论
为什么被折叠?



