在下面的代码中,我希望输出始终为1,因为我希望在poll_one()调用时只运行一个处理程序.但是,一次大约300次,输出实际上是3.根据我对boost库的理解,这似乎是不正确的.非确定性行为是错误的还是预期的?
#include <boost/asio.hpp>
int main() {
boost::asio::io_service io;
boost::asio::io_service::work io_work(io);
boost::asio::io_service::strand strand1(io);
boost::asio::io_service::strand strand2(io);
int val = 0;
strand1.post([&val, &strand2]() {
val = 1;
strand2.post([&val]() {
val = 2;
});
boost::asio::spawn(strand2, [&val](boost::asio::yield_context yield) {
val = 3;
});
});
io.poll_one();
std::cout << "Last executed: " << val << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用boost-asio 1.60.0.6
我惊讶地发现下面的代码无需io_context作为第一个参数传递给spawn. 有人可以解释一下为什么在这种情况下我不需要通过它,以及在什么情况下你必须明确通过它。我正在使用 Boost 1.75.0。
#include <boost/asio/spawn.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <iostream>
int main() {
boost::asio::io_context io_context;
boost::asio::deadline_timer timer(io_context);
boost::asio::spawn([&](boost::asio::yield_context yield){ // don't need to pass io_context?!
std::cout << "started spawn" << std::endl;
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(yield);
std::cout << "finished spawn" << std::endl;
});
std::cout << "running io_context" << std::endl;
io_context.run();
std::cout << "finished running io_context" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)