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

来源:互联网 发布:淘宝刷流量靠谱吗 编辑:程序博客网 时间:2024/05/23 19:17

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


#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;
}