/*API互斥事件对象实现线程同步*/
#include<windows.h>
#include<stdio.h>
DWORD WINAPI myfun1(LPVOID lpParameter);//声明线程函数
DWORD WINAPI myfun2(LPVOID lpParameter);
static int a=;
HANDLE hmutex;//互斥事件对象
int main()
{
HANDLE h1,h2;//定义句柄变量
hmutex=::CreateMutex(NULL,FALSE,NULL);//创建互斥事件并返回其句柄
h1=::CreateThread(NULL,,myfun1,NULL,,NULL);//创建线程1
printf("线程1开始运行!\r\n");
h2=::CreateThread(NULL,,myfun2,NULL,,NULL);//创建线程2
printf("线程2开始运行!\t\n");
::CloseHandle(h1);//关闭线程句柄对象
::CloseHandle(h2);
::Sleep();
return ;
}
DWORD WINAPI myfun1(LPVOID lpParameter)//线程函数
{
while()
{
::WaitForSingleObject(hmutex,INFINITE);//请求互斥事件
if(a<)
{
::Sleep();
a+=;
printf("线程1:%d\r\n",a);
::ReleaseMutex(hmutex);
}
else
{
::ReleaseMutex(hmutex);//释放互斥事件句柄
break;
}
}
return ;
}
DWORD WINAPI myfun2(LPVOID lpParameter)
{
while()
{
::WaitForSingleObject(hmutex,INFINITE);//请求事件对象
if(a<)
{
::Sleep();
a+=;
printf("线程2:%d\r\n",a);
::ReleaseMutex(hmutex);
}
else
{
::ReleaseMutex(hmutex);
break;
}
}
return ;
}