#include<windows.h>
#include<iostream.h>
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
);
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);
CloseHandle(hThread1);//关闭句柄, 此时系统会递减新线程的线程内核对象的使用计数, 当创建的线程
CloseHandle(hThread2);//执行完毕后, 系统也会递减线程内核对象的使用计数, 计数为0时, 系统释放线程内核对象
hMutex=CreateMutex(NULL,TRUE,NULL); //TRUE表示调用CreateMutex的线程拥有了互斥对象
WaitForSingleObject(hMutex,INFINITE);//线程多次拥有互斥对象, 主要通过互斥对象内的计数器实现
ReleaseMutex(hMutex); //申请两次则要释放两次
ReleaseMutex(hMutex); //谁申请谁释放
Sleep(1000); //要保证在卖完100张票前,主线程不能退出
}
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
)
{
while(TRUE) //保证线程的不断执行
{
WaitForSingleObject(hMutex,INFINITE); //获取信号量
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sells ticket: "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex); //释放信号量
}
return 0;
//WaitForSingleObject(hMutex,INFINITE);
//cout<<"thread1 is running! "<<endl;
//return 0;
}
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(2);
cout<<"thread2 sells ticket: "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
//WaitForSingleObject(hMutex,INFINITE);
//cout<<"thread2 is running! "<<endl;
//return 0;
}
#include<iostream.h>
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
);
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
);
int index=0;
int tickets=100;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Thread1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Thread2Proc,NULL,0,NULL);
CloseHandle(hThread1);//关闭句柄, 此时系统会递减新线程的线程内核对象的使用计数, 当创建的线程
CloseHandle(hThread2);//执行完毕后, 系统也会递减线程内核对象的使用计数, 计数为0时, 系统释放线程内核对象
hMutex=CreateMutex(NULL,TRUE,NULL); //TRUE表示调用CreateMutex的线程拥有了互斥对象
WaitForSingleObject(hMutex,INFINITE);//线程多次拥有互斥对象, 主要通过互斥对象内的计数器实现
ReleaseMutex(hMutex); //申请两次则要释放两次
ReleaseMutex(hMutex); //谁申请谁释放
Sleep(1000); //要保证在卖完100张票前,主线程不能退出
}
DWORD WINAPI Thread1Proc(
LPVOID lpParameter
)
{
while(TRUE) //保证线程的不断执行
{
WaitForSingleObject(hMutex,INFINITE); //获取信号量
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sells ticket: "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex); //释放信号量
}
return 0;
//WaitForSingleObject(hMutex,INFINITE);
//cout<<"thread1 is running! "<<endl;
//return 0;
}
DWORD WINAPI Thread2Proc(
LPVOID lpParameter
)
{
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
Sleep(2);
cout<<"thread2 sells ticket: "<<tickets--<<endl;
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
//WaitForSingleObject(hMutex,INFINITE);
//cout<<"thread2 is running! "<<endl;
//return 0;
}
改执行绿色代码。线程1虽然没释放信号量,但线程终止后,系统会自动将线程拥有的互斥 对象的线程ID设为0,将它的计数器归为0,因为OS维护线程信息和线程相关信息。所以线程2能执行。同时,通过WaitForSingleObject的返回值可知信号量是正常请求到的还是线程终止才请求到的。