码迷,mamicode.com
首页 > Windows程序 > 详细

WIN32生产消费经典同步但是以消耗时间为代价

时间:2020-06-16 20:16:31      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:multi   turn   obj   hello   class   col   bsp   tee   tchar   

// Event0616.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WINDOWS.H>
HANDLE hEvent;
HANDLE hMutex;
DWORD dwM = 10;
DWORD dSignal = 0;
DWORD WINAPI ThreadPro1(LPVOID lpParameter)
{
    for (int i =0; i < dwM; i++)
    {
        if (dSignal == 0)
        {
            WaitForSingleObject(hMutex,INFINITE);
            dSignal = 1;
            DWORD CurrentID = GetCurrentThreadId();
            printf("线程%d--生产了--%d件--产品!\n",CurrentID,dSignal);
        } 
        else
        {
            i--;
        }
        ReleaseMutex(hMutex);
    }
    return 0;
}

DWORD WINAPI ThreadPro2(LPVOID lpParameter)
{
    for (int i =0; i < dwM; i++)
    {
        if (dSignal == 1)
        {
            WaitForSingleObject(hMutex,INFINITE);
            dSignal = 0;
            DWORD CurrentID = GetCurrentThreadId();
            printf("线程%d--消费了--%d件--产品!\n",CurrentID,dSignal);
        } 
        else
        {
            i--;
        }
        ReleaseMutex(hMutex);
    }
    return 0;
}
int main(int argc, char* argv[])
{
    //1.安全属性 2.FALSE通知/TRUE互斥 3.初始有无信号TRUE有/FALSE没有 4.名字
    //hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);

    hMutex = CreateMutex(NULL,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(hEvent);
    
    //printf("Hello World!\n");
    getchar();
    return 0;
}

 

WIN32生产消费经典同步但是以消耗时间为代价

标签:multi   turn   obj   hello   class   col   bsp   tee   tchar   

原文地址:https://www.cnblogs.com/ganxiang/p/13143904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!