C++11 多线程编程 使用lambda创建std::thread (生产/消费者模式)

要写个tcp server / client的博客,想着先写个c++11多线程程序。方便后面写博客使用。

目前c++11中写多线程已经很方便了,不用再像之前的pthread_create,c++11中已经有了std::thread库可以方便使用。

直接看代码(100个任务, 多个线程处理):

 #include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <mutex> class Task{
public:
Task(int x, std::shared_ptr<std::mutex> mutex)
:_x(x), _mutex(mutex){ } void handle(){
int task_id = ;
while(true){
//获取任务, 尽早释放锁
if (_x > ){
std::lock_guard<std::mutex> lock(*_mutex);
if (_x > ){ task_id = _x; --_x; }
else { _x = ; }
}
else { return ; } //do task
std::cout << "do task id: " << task_id << std::endl;
std::this_thread::sleep_for(std::chrono::seconds());
}
}
private:
int _x;
std::shared_ptr<std::mutex> _mutex;
}; int main()
{
int x = ;
const int THREAD_NUM = ;
const int TASK_NUM = ;
std::vector<std::thread> threads; //shared_ptr 主线程与子线程可以共用一把锁.
//方便后面扩展程序(生产/消费者)
std::shared_ptr<std::mutex> mutex = std::make_shared<std::mutex>();
Task t(TASK_NUM, mutex); //新建线程, std::thread支持使用lambda
for (int i = ; i < THREAD_NUM; ++i){
threads.emplace_back(std::thread(
[&t] { t.handle(); })
);
} //等待线程结束
for(auto &thread : threads){ thread.join(); }
return ;
}

编译、执行:

g++ --std=c++11 -pthread thread.cpp

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQoAAACyCAIAAAA1RxYyAAAAA3NCSVQICAjb4U/gAAAbfElEQVR4Xu2deVxN+f/Hz7237VYqLUIJI/vaz5Yy1mzNjOVrMiGS0aRULkKTIskUpkaYyVIYJKUy1iYGGaSi0qI9LW6KaLstbsu9v3OXaDn3dpvOqdvtfR7+cT7nvD+f9/P9eZ+tz+u+SZPkdRHYgAAQwCJAxtoJ+4AAEOAQgPSAeQAEBBLASg/ZId+47rUyUsdqE2iI2AaK2tdHLpw7MUOBoG7E0GWCPAWzHSGAlQKyust3rjMaI4/V1gHbJIV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umtBCA9emvkwW8RCGClB6gFRQAHh/QGApjpAWrB3hB68LF9Aljp0f5ZIh0BasE2mEjy4zeeepeVkGQ/DP2TKGxiTwDUgriFSJhakNuJzEgzrwiHkbh1CIYIJ8C/e4BakFi1IKoXVJ25M8xB+Y9N+25VEB5V6AAnAqAW7Aq1ICKlucjXe37intWeCVq+OIUOzBBPANSCXaAWpPRf7fHzlEd7pt951yCrRXxQoQe8CHAerkAtiEUTN7Ugud98B4+J8bsOP4VSm1igxXkf990D1IIEhoikPMdifl+l2Rei4qrRn7pK8l+jjAyzC3kfsnIQv9gggZ2D6c4R4KQHqAWxGOKlFmRXhDusmLxkJf/f//beqUEKL28z3Hq3CH7LBwu8OO0DtSDxakFGYV7655hTVcrrkU8f32QVMqD0pjhlAuZYQC3YRiDJ44SjWhATPOzsCQRALdgTogRj7CYC/w/rSw/MeUSetgAAAABJRU5ErkJggg==" alt="" />

上一篇:poj-2421-最小生成树刷题


下一篇:C# 线程池ThreadPool的用法简析