您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-07 20:46 351 查看
#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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息