百思不得其解。。。求鞭挞,求解救
我头疼啊。。。为什么不能够实现互斥。。。。菜菜求大神指点
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
bool g_continue=true;
int n,m,t=0;
int k=1;
int a[10];
int b[10];
DWORD WINAPI Thread1(LPVOID lpPara); //线程1
DWORD WINAPI Thread2(LPVOID lpPara); //线程1
HANDLE huchi;
int main(){
HANDLE hThread1, hThread2;//两个线程的handle
DWORD ThreadId1, ThreadId2; //两个线程的线程ID
huchi=CreateMutex(NULL,FALSE,NULL);
hThread1 = CreateThread(NULL,0,Thread1,NULL,0,&ThreadId1); //创建线程1
if(hThread1 == NULL)
return -1;
hThread2 = CreateThread(NULL,0,Thread2,NULL,0,&ThreadId2); //创建线程2
if(hThread2 == NULL)
return -1;
if(getchar()){ //按回车后终止程序运行
g_continue = false;
}
//等待子进程结束
WaitForSingleObject(hThread1,INFINITE);
WaitForSingleObject(hThread2,INFINITE);
//释放子进程资源
CloseHandle(hThread1);
CloseHandle(hThread2);
system("pause");
}
//线程1执行的代码
DWORD WINAPI Thread1(LPVOID lpPara)
{
WaitForSingleObject(huchi,INFINITE);
while(g_continue)
{
for(n=0;n<10;n++)
{if (a[n]==0)
{a[n]=1;
b[n]=k;
k=k+1;
break;}}
cout<<"生产者将生产编号"<<k-1<<"放入缓冲单元"<<n<<endl;
cout<<"缓冲单元编号"<<" 产品编号 "<<"缓冲单元状态"<<endl;
for(n=0;n<10;n++)
{cout<<" "<<n<<" "<<b[n]<<" "<<a[n]<<endl;}
ReleaseMutex (huchi);
}
return 0;
}
//线程2执行的代码
DWORD WINAPI Thread2(LPVOID lpPara)
{
WaitForSingleObject(huchi,INFINITE);
while(g_continue)
{
for(n=0;n<10;n++)
{if (a[m]==1)
{a[m]=0;
t=b[m];
b[m]=0;
break;}}
cout<<"消费者从缓冲单元"<<m<<"将产品"<<t<<"取出"<<endl;
cout<<"缓冲单元编号"<<" 产品编号 "<<"缓冲单元状态"<<endl;
for(m=0;m<10;m++)
{cout<<" "<<m<<" "<<b[m]<<" "<<a[m]<<endl;}
ReleaseMutex (huchi);
}
return 0;
}