各位大侠,请看下面代码:
int tickets=100;//定义全局变量tickets
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);//创建线程1
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);//创建线程2
hMutex=CreateMutex(NULL,TRUE,NULL);//创建互斥对象
Sleep(4000);}DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
} return 0;
}DWORD WINAPI Fun2Proc(LPVOID lpParameter )
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
结果是交替输出thread2 sell ticket : 100
thread1 sell ticket : 99
thread2 sell ticket : 98
thread1 sell ticket : 97
我的问题是为什么两个线程能恰好交替执行呢?当线程1的执行函数ReleaseMutex(hMutex)后,hMutex变为有信号,但是两个线程都在WaitForSingleObject(hMutex,INFINITE)也就是说两线程都在争夺hMutex啊,为什么就能恰好一个释放后另一个线程恰好得到hMutex呢?补充问题,为什么是线程2先输出呢?明明是线程1先创建的啊,还有我把sleep(1)都注释掉后输出thread1 sell ticket : 100
thread1 sell ticket : 99
后面是交替输出的,望指教!
int tickets=100;//定义全局变量tickets
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);//创建线程1
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);//创建线程2
hMutex=CreateMutex(NULL,TRUE,NULL);//创建互斥对象
Sleep(4000);}DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
} return 0;
}DWORD WINAPI Fun2Proc(LPVOID lpParameter )
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
结果是交替输出thread2 sell ticket : 100
thread1 sell ticket : 99
thread2 sell ticket : 98
thread1 sell ticket : 97
我的问题是为什么两个线程能恰好交替执行呢?当线程1的执行函数ReleaseMutex(hMutex)后,hMutex变为有信号,但是两个线程都在WaitForSingleObject(hMutex,INFINITE)也就是说两线程都在争夺hMutex啊,为什么就能恰好一个释放后另一个线程恰好得到hMutex呢?补充问题,为什么是线程2先输出呢?明明是线程1先创建的啊,还有我把sleep(1)都注释掉后输出thread1 sell ticket : 100
thread1 sell ticket : 99
后面是交替输出的,望指教!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货