C++多线程学习笔记004简单的Producer和Consumer模型

2023-12-24 22:37:04

C++多线程学习笔记004简单的Producer和Consumer模型

引言

Producer为队列中添加“任务”,Consumer自队列中取出并完成“任务”。

实列代码

#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
#include<condition_variable>
#include<queue>

std::queue<int> queue1;
std::condition_variable condtval1;
std::mutex mtx;

void Producer() {
    for(int i = 0; i < 10; i++){
        {   
            std::unique_lock<std::mutex> unlck(mtx);
            queue1.push(i);
            condtval1.notify_one();
            std::cout << "Producer : " << i << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

void Consumer() {
    while(1){
        std::unique_lock<std::mutex> unlck(mtx);
        condtval1.wait(unlck, [] () {return !queue1.empty();});
        int val = queue1.front();
        queue1.pop();
        std::cout << "Consumer : " << val << std::endl;
    }
}

int num {0};



int main(){

    std::thread thread1(Producer);
    std::thread thread2(Consumer);
    thread1.join();
    thread2.join();
    std::cout <<"over" << std::endl;
    return 0;
}
// g++ ./XXX.cpp -o ./XXX -pthread

文章来源:https://blog.csdn.net/weixin_43111445/article/details/135187064
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。