inttest(int a, int b){ std::this_thread::sleep_for(std::chrono::seconds(1)); std::lock_guard<std::mutex> lock(g_screen_mutex); std::cout << "test() at thread [ " << std::this_thread::get_id() << "] output [" << a + b << "]" << std::endl; return a + b; }
intmain(){ thread_pool thread_pool; std::vector<std::future<int>> results; for(int i = 0; i < 5 ; i++) { auto fu = thread_pool.add_task(test, i, 2); results.emplace_back(std::move(fu)); } getchar(); // 等待,不要让主进程退出 for (int i = 0; i < 5; i++) { std::cout<< "result of number " << i << " :" << results[i].get() << std::endl; } return0; }
@└────> # ./test.out thread_pool::threadLoop() tid : 139812637472512 start. thread_pool::take() tid : 139812637472512 wakeup. thread_pool::take() tid : 139812637472512 took a task! thread_pool::threadLoop() tid : 139812629079808 start. thread_pool::take() tid : 139812629079808 wakeup. thread_pool::take() tid : 139812629079808 took a task! thread_pool::threadLoop() tid : 139812620687104 start. thread_pool::take() tid : 139812620687104 wakeup. thread_pool::take() tid : 139812620687104 took a task! test() at thread [ 139812637472512] output [2] thread_pool::take() tid : 139812637472512 wakeup. thread_pool::take() tid : 139812637472512 took a task! test() at thread [ 139812629079808] output [3] thread_pool::take() tid : 139812629079808 wakeup. thread_pool::take() tid : 139812629079808 took a task! test() at thread [ 139812620687104] output [4] thread_pool::take() tid : 139812620687104 wait. test() at thread [ 139812637472512] output [5] thread_pool::take() tid : 139812637472512 wait. test() at thread [ 139812629079808] output [6] thread_pool::take() tid : 139812629079808 wait. (键入回车) result of number 0 :2 result of number 1 :3 result of number 2 :4 result of number 3 :5 result of number 4 :6 thread_pool::stop() stop. thread_pool::stop() notifyAll(). thread_pool::take() tid : 139812620687104 wakeup. thread_pool::threadLoop() tid : 139812620687104 exit. thread_pool::take() tid : 139812637472512 wakeup. thread_pool::threadLoop() tid : 139812637472512 exit. thread_pool::take() tid : 139812629079808 wakeup. thread_pool::threadLoop() tid : 139812629079808 exit.