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