zoukankan      html  css  js  c++  java
  • 生产者消费者C++实现

    #include<string>
    #include<iostream>
    #include<process.h>
    #include<windows.h>
    #include <stdlib.h>
    #include<time.h>
    #include<list>
    using namespace std;
    HANDLE empty,full; //同步信号量 缓冲池的剩余 缓冲池中的产品个数 生产者与消
    费者同步
    HANDLE mutex;//互斥信号量,生产者与生产者互斥,消费者与消费者互斥
    int buf_max=5; //缓冲池大小
    int product=0; //产品数量
    typedef list<int> LISTINT;
    LISTINT Buffer;
    LISTINT::iterator i;
    int getRandom()
    {
    return rand()%23;
    }
    void printBuffer()
    {
    cout<<"现在缓冲池中有:";
    for (i = Buffer.begin(); i != Buffer.end(); ++i)
    cout << *i << ",";
    cout<<endl;
    }
    //生产者线程
    unsigned __stdcall threadProducer(void *)
    {
    for(int i = 0; i < 5; i++){
    Sleep(getRandom()*10);
    WaitForSingleObject(empty, INFINITE);//等待同步信号量empty
    WaitForSingleObject(mutex, INFINITE);//等待互斥信号量mutex
    product++;
    int p=getRandom();
    Buffer.push_front(p);
    cout<<"生产者生产了"<<p<<" ";
    printBuffer();
    Sleep(100);
    ReleaseSemaphore(mutex, 1, NULL);//释放互斥信号量mutex
    ReleaseSemaphore(full, 1, NULL);//释放同步信号量full
    }
    return 1;
    }
    //消费者线程
    unsigned __stdcall threadConsumer(void *)
    {
    for(int i = 0; i < 5; i++){
    Sleep(getRandom()*10);
    WaitForSingleObject(full, INFINITE);//等待同步信号量full
    WaitForSingleObject(mutex, INFINITE);//等待互斥信号量mutex
    product--;
    cout<<"消费者消费了产品"<<Buffer.back()<<" ";
    Buffer.pop_back();
    printBuffer();
    Sleep(100);
    ReleaseSemaphore(mutex, 1, NULL);//释放互斥信号量mutex
    ReleaseSemaphore(empty, 1, NULL);//释放信号量
    }
    return 2;
    }

    void main()
    {
    bool flag=false;
    while(!flag)
    {
    cout<<"缓冲池大小为"<<buf_max<<endl;
    if(buf_max<=0);
    else flag=true;
    }
    //创建信号量
    empty = CreateSemaphore(NULL, buf_max, buf_max, NULL);//初值为缓冲池大
    小,最大为缓冲池大小
    full = CreateSemaphore(NULL, 0, buf_max, NULL); //初值为0,最大
    为缓冲池大小
    mutex = CreateSemaphore(NULL,1,1,NULL); //初值为1,最大为
    1
    HANDLE hth1, hth2; //线程句柄

    //创建线程
    hth1 = (HANDLE)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)
    threadProducer, NULL, 0, NULL);//生产者线程
    hth2 = (HANDLE)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)
    threadConsumer, NULL, 0, NULL);//消费者线程

    //等待子线程结束
    WaitForSingleObject(hth1, INFINITE);
    WaitForSingleObject(hth2, INFINITE);

    //关闭句柄
    CloseHandle(hth1);
    CloseHandle(hth2);
    CloseHandle(empty);
    CloseHandle(full);
    CloseHandle(mutex);
    }

  • 相关阅读:
    Linux进程理解与实践(四)wait函数处理僵尸进程
    Linux进程理解与实践(三)进程终止函数和exec函数族的使用
    system V信号量和Posix信号量
    Linux进程间通信方式--信号,管道,消息队列,信号量,共享内存
    linux 高并发socket通信模型
    信号集函数
    进程间通信使用信号
    使用消息队列
    改变域名,php
    php函数
  • 原文地址:https://www.cnblogs.com/lancelee98/p/9918332.html
Copyright © 2011-2022 走看看