生产消费模型实例C++11

#include <iostream>                // std::cout
#include <thread>                // std::thread
#include <mutex>                // std::mutex, std::unique_lock
#include <condition_variable>    // std::condition_variable
#include <chrono>
#include <unistd.h>

std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量. 
using namespace std;

void consumer(int id)
{
    std::unique_lock <std::mutex> lck(mtx);
    while (true)
    {
        cout << "read " << id << endl;
        cv.wait(lck);  
    }
    // 线程被唤醒, 继续往下执行打印线程编号id.
    std::cout << "thread " << id << '\n';
}

void go()
{
    cout << "tell consumer to process. " <<endl; 
    cv.notify_all(); // 唤醒所有线程.
}

void
producer(){
    int ok;
    while(1)
    {
        cin >> ok;
        cout <<"ok is"<< ok ;
        if(ok){
            std::cout << "10 threads ready to race...\n";
            sleep(2);
            go(); // go!
        }
        ok = 0;
    }
}


int main()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(consumer, i);
    

    producer();

    
    for (auto & th:threads)
        th.join();

    return 0;
}



这里不做文字说明,此时的文字说明显得有些多余。GCC需要在4.8+,以便支持c++11。

需要注意的是,常见的代码实现的 生产消费者模型都是消费者线程轮询产品的方式。从系统性能和原理上面来看,都是不完美的。

cmake脚本如下

PROJECT(sample)
set (CMAKE_CXX_STANDARD 11)
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
    message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif() 
 
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)

#本地目录
INCLUDE_DIRECTORIES(".")
FILE(GLOB root "./*.cpp")


link_directories("/usr/lib/x86_64-linux-gnu/") 

AUX_SOURCE_DIRECTORY(. DIR_SRCS)

ADD_EXECUTABLE(sample ${DIR_SRCS} ${root} )

TARGET_LINK_LIBRARIES(sample m -lpthread)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值