for (int i = 0; i < 10; ++i) { boost::asio::post(ioc, std::bind(func, i)); }
std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::vector<std::thread> threads; for (int i = 0; i < 3; ++i) threads.emplace_back(worker_thread, std::ref(ioc));
for (auto& thread : threads) { thread.join(); } }
输出结果:
1 2 3 4 5 6 7 8 9 10
thread 8716, func called i = 2 thread 18312, func called i = 3 thread 5140, func called i = 1 thread 8716, func called i = 4 thread 18312, func called i = 5 thread 8716, func called i = 6 thread 5140, func called i = 7 thread 18312, func called i = 8 thread 8716, func called i = 9 thread 11660, func called i = 0
for (int i = 0; i < 10; ++i) { boost::asio::post(strand, std::bind(func, i)); }
输出结果:
1 2 3 4 5 6 7 8 9 10
thread 17548, func called i = 0 thread 18284, func called i = 1 thread 18284, func called i = 2 thread 18284, func called i = 3 thread 18284, func called i = 4 thread 18284, func called i = 5 thread 18284, func called i = 6 thread 18284, func called i = 7 thread 18284, func called i = 8 thread 18284, func called i = 9