c++多线程挂起与唤醒

基本思想:自用脚本,可实现c++多线程之间挂起与唤醒

CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(test_tcp)
set(CMAKE_CXX_STANDARD 14)
add_executable(test_tcp main.cpp)
target_link_libraries(test_tcp -lpthread)

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
using namespace std;

const int max_size = 1;
int products= 0;
std::mutex product_mutex;
std::condition_variable cv;

void Productor() {
    int num = 0;
    while(true) {
        std::unique_lock<std::mutex> lk(product_mutex);
        cv.wait(lk, []() { return products== 0; });
        cout << "生产线程id: " << std::this_thread::get_id() << endl;
        while (true){
            std::this_thread::sleep_for(1000ms);
            //摄像头1 
            std::cout<<"camera 1"<<std::endl;
            break;
        }
        products=1;
        lk.unlock();
        cv.notify_all();
    }
}

void Consumer() {
    while (true) {
        std::unique_lock<std::mutex> lk(product_mutex);
        cv.wait(lk, []() { return products==1; });
        cout << "消费线程id:"<<std::this_thread::get_id()<< endl;

         while (true){
                    std::this_thread::sleep_for(3000ms);
                    //摄像头2
                    std::cout<<"camera 2"<<std::endl;
                    break;
                }
                products= 2;
      			lk.unlock();
        		cv.notify_all();
    }
}

void Consumer1() {
    while (true) {
        std::unique_lock<std::mutex> lk(product_mutex);
        cv.wait(lk, []() { return products==2; });
        cout << "消费线程id:"<<std::this_thread::get_id()<< endl;

        while (true){
            std::this_thread::sleep_for(3000ms);
            //摄像头2
            std::cout<<"camera 3"<<std::endl;
            break;
        }
        products= 0;
        lk.unlock();
        cv.notify_all();
    }
}

int main()
{
    thread th1(Productor);
    thread th2(Consumer);
    thread th3(Consumer1);
    th1.join();
    th2.join();
    th3.join();
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值