Windows系统的多线程同步 Win32 Console Application

操作系统实验课所写的代码:


#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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值