[C++] socket - 6 [API互斥事件对象实现线程同步]

 

 

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

 

posted @ 2014-03-18 14:36  beautifulzzzz  阅读(520)  评论(0编辑  收藏  举报