您在发布第一个任务后加入池。因此,池在您接受第二个任务之前就停止了。这就解释了为什么你没有看到更多。
这解决了这个问题:
for (size_t i = 0; i != 50; ++i) {
post(g_pool, boost::bind(f, 10 * i));
}
g_pool.join();
附录#1
响应 cmets。如果您想等待特定任务的结果,请考虑未来:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <future>
boost::asio::thread_pool g_pool(10);
int f(int i) {
std::cout << '(' + std::to_string(i) + ')';
return i * i;
}
int main() {
std::cout << std::unitbuf;
std::future<int> answer;
for (size_t i = 0; i != 50; ++i) {
auto task = boost::bind(f, 10 * i);
if (i == 42) {
answer = post(g_pool, std::packaged_task<int()>(task));
} else
{
post(g_pool, task);
}
}
answer.wait(); // optionally make sure it is ready before blocking get()
std::cout << "\n[Answer to #42: " + std::to_string(answer.get()) + "]\n";
// wait for remaining tasks
g_pool.join();
}
只有一种可能的输出:
(0)(50)(30)(90)(110)(100)(120)(130)(140)(150)(160)(170)(180)(190)(40)(200)(210)(220)(240)(250)(70)(260)(20)(230)(10)(290)(80)(270)(300)(340)(350)(310)(360)(370)(380)(330)(400)(410)(430)(60)(420)(470)(440)(490)(480)(320)(460)(450)(390)
[Answer to #42: 176400]
(280)
附录 #2:序列化任务
如果要序列化特定任务,可以使用 strand。例如。根据参数的余数模3序列化所有请求:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <future>
boost::asio::thread_pool g_pool(10);
int f(int i) {
std::cout << '(' + std::to_string(i) + ')';
return i * i;
}
int main() {
std::cout << std::unitbuf;
std::array strands{make_strand(g_pool.get_executor()),
make_strand(g_pool.get_executor()),
make_strand(g_pool.get_executor())};
for (size_t i = 0; i != 50; ++i) {
post(strands.at(i % 3), boost::bind(f, i));
}
g_pool.join();
}
有一个可能的输出:
(0)(3)(6)(2)(9)(1)(5)(8)(11)(4)(7)(10)(13)(16)(19)(22)(25)(28)(31)(34)(37)(40)(43)(46)(49)(12)(15)(14)(18)(21)(24)(27)(30)(33)(36)(39)(42)(45)(48)(17)(20)(23)(26)(29)(32)(35)(38)(41)(44)(47)
请注意,所有工作都在任何线程上完成,但链上的任务按照它们发布的顺序发生。所以,
- 0、3、6、9、12...
- 1、4、7、10、13...
- 2、5、8、11、14...
虽然严格按顺序发生
- 4 和 7 不需要在同一个物理线程上发生
- 11 可能发生在 4 之前,因为它们不在同一条链上
更多
如果您需要更多“类似屏障”的同步,或者所谓的 fork-join 语义,请参阅 Boost asio thread_pool join does not wait for tasks to be finished(我在其中发布了两个答案,一个是在我发现 fork-join 执行器示例之后)。