zoukankan      html  css  js  c++  java
  • 简单的生产者消费者-(windows下)

    // Produce_Consume.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include "windows.h"
    #include <process.h>//_beginthreadex的头文件

    #define BUFFER_SIZE 10


    HANDLE hMutex;
    HANDLE hNotFull;
    HANDLE hNotEmpty;

    struct prodcons
    {
      int buffer[BUFFER_SIZE];
      int getpos, putpos;
    };

    typedef struct prodcons PrCon;

    PrCon *pContainer;

    unsigned __stdcall Producer(void *mArgclist)
    {

     while(1)
     {
      WaitForSingleObject(hNotFull, INFINITE);
      WaitForSingleObject(hMutex,INFINITE);//

      pContainer->buffer[pContainer->putpos] = pContainer->putpos;
      pContainer->putpos = (pContainer->putpos+1)%BUFFER_SIZE;
      

      ReleaseMutex(hMutex);
      ReleaseSemaphore(hNotEmpty , 1 , NULL);

     }
     
     return 1;
    }

    unsigned __stdcall Consumer(void *mArgclist)
    {
     
     int data;
     while(1)
     {
      WaitForSingleObject(hNotEmpty, INFINITE);
      WaitForSingleObject(hMutex,INFINITE);//

      data = pContainer->buffer[pContainer->getpos];
      pContainer->getpos = (pContainer->getpos+1)%BUFFER_SIZE;
      
      ReleaseMutex(hMutex);
      ReleaseSemaphore(hNotFull , 1, NULL);
      printf("GetData=%d " , data);
     }
     
     return 1;
    }

    int main(void)
    {
     HANDLE hProThread , hConThread;
     unsigned int ProducerId , ConsumerId;
     PrCon Container;
     
     Container.putpos = Container.getpos=0;
     pContainer = &Container;

     hNotFull = CreateSemaphore(NULL, 10, 10, _T("NotFull"));
     hNotEmpty = CreateSemaphore(NULL, 0, 10, _T("NotEmpty"));

     hMutex = CreateMutex(NULL, FALSE, _T("Mutex")); 
     if (GetLastError() == ERROR_ALREADY_EXISTS)
     {
      // 如果已有互斥量存在则释放句柄并复位互斥量
      CloseHandle(hMutex);
      hMutex = NULL; 
      return FALSE;
     }


     hProThread = (HANDLE)_beginthreadex(NULL,0,&Producer,NULL,NULL , &ProducerId);
     hConThread = (HANDLE)_beginthreadex(NULL,0,&Consumer,NULL,NULL , &ConsumerId);

     printf("enter any key to exit... ");
     getchar();

    }

  • 相关阅读:
    element ui 权限 全选和半选
    div 内容垂直居中
    ajax 传递list2
    mysql学习03-sql执行加载顺序
    mysql学习02-mysql存储引擎(InnoDB,MyISAM)
    mysql学习01-mysql架构
    没有项目的源码,在eclipse下进行tomcat的远程调试,小计一下。
    win10系统,使用SangforHelperTool诊断工具进行修复时,无法安装虚拟网卡。
    postman在有登录认证的情况下进行接口测试!!!
    MongoDB4.0及以上的版本安装时无法启动服务。
  • 原文地址:https://www.cnblogs.com/ju-an/p/3269943.html
Copyright © 2011-2022 走看看