zoukankan      html  css  js  c++  java
  • WIN通过消息实现互斥同步CreateEvent和SetEvent

    // Event0616.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <WINDOWS.H>
    #include <iostream>
    HANDLE hEventSet;
    HANDLE hEventClear;
    //HANDLE hMutex;
    DWORD dwM = 10;
    DWORD dSignal = 0;
    DWORD WINAPI ThreadPro1(LPVOID lpParameter)
    {
        for (int i =0; i < dwM; i++)
        {
            WaitForSingleObject(hEventSet,INFINITE);
            dSignal = 1;
            DWORD CurrentID = GetCurrentThreadId();
            fflush(stdin);
            printf("线程%d--生产了--%d件--产品!\n",CurrentID,dSignal);
            SetEvent(hEventClear);
        }
        return 0;
    }
    
    DWORD WINAPI ThreadPro2(LPVOID lpParameter)
    {
        for (int j =0; j < dwM; j++)
        {
            WaitForSingleObject(hEventClear,INFINITE);
            dSignal = 0;
            DWORD CurrentID = GetCurrentThreadId();
            fflush(stdin);
            printf("线程%d--消费了--%d件--产品!\n",CurrentID,dSignal);
            SetEvent(hEventSet);
        }
        return 0;
    }
    int main(int argc, char* argv[])
    {
        //1.安全属性 2.FALSE通知/TRUE互斥 3.初始有无信号TRUE有/FALSE没有 4.名字
        //hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
    
        hEventSet = CreateEvent(NULL,FALSE,TRUE,NULL);
        hEventClear = CreateEvent(NULL,FALSE,FALSE,NULL);
        
        HANDLE hThead[2];
        hThead[0] = ::CreateThread(NULL,0,ThreadPro1,NULL,0,NULL);
        hThead[1] = ::CreateThread(NULL,0,ThreadPro2,NULL,0,NULL);
        
        //SetEvent(hEvent);
        
        WaitForMultipleObjects(sizeof(hThead),hThead,TRUE,INFINITE);
        
        CloseHandle(hThead[0]);
        CloseHandle(hThead[1]);
        CloseHandle(hEventSet);
        CloseHandle(hEventClear);
    
        
        //printf("Hello World!\n");
        getchar();
        //system("pause");
        return 0;
    }
  • 相关阅读:
    Online
    C语言的原码,反码,补码
    PHP常用函数
    [javascript] npx 命令简单使用
    [javascript] vue的实例生命周期钩子函数
    curl扩展post请求http接口报错:failed creating formpost data
    [javascript] 基于elementui的后台界面开发
    [javascript] var let const声明变量的区别
    [PHP] 实现oauth下的单点登陆
    [日常] KRA与KPI 绩效考核
  • 原文地址:https://www.cnblogs.com/ganxiang/p/13149806.html
Copyright © 2011-2022 走看看