死锁解决C语言程序
发布网友
发布时间:2022-04-09 23:46
我来回答
共1个回答
热心网友
时间:2022-04-10 01:15
#include <windows.h>
#include <iostream>
#include<time.h>
const unsigned short SIZE_OF_BUFFER = 1; //缓冲区长度
int g_buffer[SIZE_OF_BUFFER];
bool g_continue = true; //控制程序结束
HANDLE g_hMutex; //用于线程间的互斥
DWORD WINAPI FatherProc(LPVOID); //父进程线程
DWORD WINAPI SonProc(LPVOID); //使用打印机的线程
int main()
{
//创建各个互斥信号
g_hMutex = CreateMutex(NULL,FALSE,NULL);
const unsigned short FATHERS_COUNTS = 1; //父进程线程的个数
const unsigned short SONS_COUNT = 2; //使用打印机的线程的个数
//总的线程数
const unsigned short THREADS_COUNT = FATHERS_COUNTS+SONS_COUNT;
HANDLE hThreads[THREADS_COUNT]; //各线程的handle
DWORD fatherID[FATHERS_COUNTS]; //父进程线程的标识符
DWORD sonID[SONS_COUNT]; //使用打印机的线程的标识符
//父进程线程
for (int i=0;i<FATHERS_COUNTS;++i){
hThreads[i]=CreateThread(NULL,0,FatherProc,NULL,0,&fatherID[i]);
if (hThreads[i]==NULL) return -1;
}
//使用打印机的线程
for (i=0;i<SONS_COUNT;++i){
hThreads[SONS_COUNT+i]=CreateThread(NULL,0,SonProc,NULL,0,&sonID[i]);
if (hThreads[i]==NULL) return -1;
}
while(g_continue){
if(getchar())
{ //按回车后终止程序运行
g_continue = false;
}
}
return 0;
}
//分配打印机
void Append()
{
srand((unsigned)time(0));
std::cerr << "打印机空闲 ...\n";
if(rand()%2)
{
g_buffer[0]=1;//给PA
}
else
{
g_buffer[0]=0;//给PB
}
}
//son使用打印机
void Take()
{
if(g_buffer[0]==1)
{
std::cerr << "PA使用打印机 ... ";
std::cerr << "成功" << std::endl<<std::endl; ;
};
if(g_buffer[0]==0)
{
std::cerr << "PB使用打印机 ... ";
std::cerr << "成功" << std::endl<<std::endl; ;
};
g_buffer[0]=-1;
}
//父进程
DWORD WINAPI FatherProc(LPVOID lpPara)
{
while(g_continue){
WaitForSingleObject(g_hMutex,INFINITE);
Append();
Sleep(1500);
ReleaseMutex(g_hMutex);
}
return 0;
}
//子进程
DWORD WINAPI SonProc(LPVOID lpPara)
{
while(g_continue){
WaitForSingleObject(g_hMutex,INFINITE);
Take();
Sleep(1500);
ReleaseMutex(g_hMutex);
}
return 0;
} 最后的要求自己添加