美文网首页
事件实现同步

事件实现同步

作者: Fa1se003 | 来源:发表于2017-04-24 14:54 被阅读8次
    #include "stdafx.h"
    #include <windows.h>
    HANDLE g_hSet = NULL;
    HANDLE g_hClean = NULL;
    
    int g_max = 10;
    int g_num = 0;
    
    DWORD WINAPI t1(LPVOID lpargv)
    {
            for(int i =0;i<g_max;i++)
            {
                    WaitForSingleObject(g_hSet,INFINITE);
                    g_num = 1;
                    //Sleep(100);
                    printf("线程1执行了 %d\n",g_num);
                    SetEvent(g_hClean);
                    
            }
            return 0;
    }
    
    DWORD WINAPI t2(LPVOID lpargv)
    {
            for(int i =0;i<g_max;i++)
            {
                    WaitForSingleObject(g_hClean,INFINITE);
                    g_num = 0;
                    //Sleep(100);
                    printf("线程2执行了 %d\n",g_num);
                    SetEvent(g_hSet);
            }
            return 0;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
            //第二个参数true通知类型,false互斥类型
            g_hSet = CreateEvent(NULL,FALSE,TRUE,NULL);
            g_hClean = CreateEvent(NULL,FALSE,FALSE,NULL);
            
            HANDLE hThread[2];
            hThread[0] = CreateThread(NULL,0,t1,NULL,0,NULL);
            hThread[1] = CreateThread(NULL,0,t2,NULL,0,NULL);
    
            WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
    
            CloseHandle(hThread[0]);
            CloseHandle(hThread[1]);
            CloseHandle(g_hSet);
            CloseHandle(g_hClean);
            return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:事件实现同步

          本文链接:https://www.haomeiwen.com/subject/iblpzttx.html