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

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

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

 

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

 1 #include <iostream>
 2 #include <thread>
 3 #include <chrono>
 4 #include <vector>
 5 #include <mutex>
 6  
 7 class Task{
 8 public:
 9     Task(int x, std::shared_ptr<std::mutex> mutex)
10             :_x(x), _mutex(mutex){ }
11     
12     void handle(){
13         int task_id = 0;
14         while(true){
15             //获取任务, 尽早释放锁
16             if (_x > 0){ 
17                 std::lock_guard<std::mutex> lock(*_mutex);
18                 if (_x > 0){ task_id = _x; --_x; }
19                 else { _x = 0; }
20             }   
21             else { return ; } 
22 
23             //do task
24             std::cout << "do task id: " << task_id << std::endl;
25             std::this_thread::sleep_for(std::chrono::seconds(1));
26         }   
27     }   
28 private:
29     int _x; 
30     std::shared_ptr<std::mutex> _mutex;
31 };
32 
33 int main()
34 {
35     int x = 0;
36     const int THREAD_NUM = 7;
37     const int TASK_NUM = 100;
38     std::vector<std::thread> threads;
39 
40     //shared_ptr 主线程与子线程可以共用一把锁.
41     //方便后面扩展程序(生产/消费者)
42     std::shared_ptr<std::mutex> mutex = std::make_shared<std::mutex>();
43     Task t(TASK_NUM, mutex);
44 
45     //新建线程, std::thread支持使用lambda
46     for (int i = 0; i < THREAD_NUM; ++i){
47         threads.emplace_back(std::thread(
48             [&t] { t.handle(); })
49         );
50     }
51 
52     //等待线程结束
53     for(auto &thread : threads){ thread.join(); }
54     return 0;
55 }

编译、执行:

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值