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

无情 阅读:839 2020-10-15 10:16:58 评论:0

要写个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

标签:C++
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号