我的问题是,如果我在多个线程上运行 io_service::run(),我是否需要对这些异步函数实现阻塞?
示例:
int i = 0;
int j = 0;
void test_timer(boost::system::error_code ec)
{
//I need to lock up here ?
if (i++ == 10)
{
j = i * 10;
}
timer.expires_at(timer.expires_at() + boost::posix_time::milliseconds(500));
timer.async_wait(&test_timer);
}
void threadMain()
{
io_service.run();
}
int main()
{
boost::thread_group workers;
timer.async_wait(&test_timer);
for (int i = 0; i < 5; i++){
workers.create_thread(&threadMain);
}
io_service.run();
workers.join_all();
return 0;
}
最佳答案
异步的定义是它是非阻塞的。
如果您想问“我是否必须同步从不同线程对共享对象的访问”,那么这个问题是无关的,答案取决于您正在共享的对象的线程安全记录。
对于 Asio,基本上(粗略总结)您需要同步并发访问(并发:来自多个线程)到除 boost::asio::io_context
之外的所有类型 1,2。
您的样本
您的示例使用多个线程运行 io 服务,这意味着处理程序在任何这些线程上运行。这意味着您实际上正在共享全局变量,并且它们确实需要保护。
但是因为您的应用程序逻辑(异步调用链)规定只有一个操作处于待处理状态,并且共享计时器对象上的下一个异步操作是 始终从该链内调度,访问逻辑上全部来自单个线程(称为隐式链。请参阅Why do I need strand per connection when using boost::asio?
最简单的可行方法:
逻辑链
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
boost::asio::io_service io_service;
boost::asio::deadline_timer timer { io_service };
struct state_t {
int i = 0;
int j = 0;
} state;
void test_timer(boost::system::error_code ec)
{
if (ec != boost::asio::error::operation_aborted) {
{
if (state.i++ == 10) {
state.j = state.i * 10;
if (state.j > 100)
return; // stop after 5 seconds
}
}
timer.expires_at(timer.expires_at() + boost::posix_time::milliseconds(50));
timer.async_wait(&test_timer);
}
}
int main()
{
boost::thread_group workers;
timer.expires_from_now(boost::posix_time::milliseconds(50));
timer.async_wait(&test_timer);
for (int i = 0; i < 5; i++){
workers.create_thread([] { io_service.run(); });
}
workers.join_all();
std::cout << "i = " << state.i << std::endl;
std::cout << "j = " << state.j << std::endl;
}
Note I removed the
io_service::run()
from the main thread as it is redundant with thejoin()
(unless you really wanted 6 threads running the handlers, not 5).
打印
i = 11
j = 110
警告
这里潜伏着一个陷阱。比如说,您不想像我一样以固定的数字保释,但想停下来,您可能会这样做:
timer.cancel();
来自 main
。这是不合法的,因为 deadline_timer
对象不是线程安全的。你需要要么
- 使用全局
atomic_bool
发出终止请求 - 发布
timer.cancel()
与计时器异步链位于同一链上。但是,只有显式链,因此如果不更改代码以使用显式链,则无法做到这一点。
更多计时器
让我们通过使用两个计时器以及它们自己的隐式链来使事情变得复杂。这意味着对计时器实例的访问仍然不需要同步,但对 i
的访问需要同步。和j
确实需要。
Note In this demo I use
synchronized_value<>
for elegance. You can write similar logic manually usingmutex
andlock_guard
.
<强> Live On Coliru
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/thread/synchronized_value.hpp>
#include <iostream>
boost::asio::io_service io_service;
struct state {
int i = 0;
int j = 0;
};
boost::synchronized_value<state> shared_state;
struct TimerChain {
boost::asio::deadline_timer _timer;
TimerChain() : _timer{io_service} {
_timer.expires_from_now(boost::posix_time::milliseconds(50));
resume();
}
void resume() {
_timer.async_wait(boost::bind(&TimerChain::test_timer, this, _1));
};
void test_timer(boost::system::error_code ec)
{
if (ec != boost::asio::error::operation_aborted) {
{
auto state = shared_state.synchronize();
if (state->i++ == 10) {
state->j = state->i * 10;
}
if (state->j > 100) return; // stop after some iterations
}
_timer.expires_at(_timer.expires_at() + boost::posix_time::milliseconds(50));
resume();
}
}
};
int main()
{
boost::thread_group workers;
TimerChain timer1;
TimerChain timer2;
for (int i = 0; i < 5; i++){
workers.create_thread([] { io_service.run(); });
}
workers.join_all();
auto state = shared_state.synchronize();
std::cout << "i = " << state->i << std::endl;
std::cout << "j = " << state->j << std::endl;
}
打印
i = 12
j = 110
添加显式链
现在添加它们非常简单:
struct TimerChain {
boost::asio::io_service::strand _strand;
boost::asio::deadline_timer _timer;
TimerChain() : _strand{io_service}, _timer{io_service} {
_timer.expires_from_now(boost::posix_time::milliseconds(50));
resume();
}
void resume() {
_timer.async_wait(_strand.wrap(boost::bind(&TimerChain::test_timer, this, _1)));
};
void stop() { // thread safe
_strand.post([this] { _timer.cancel(); });
}
// ...
<强> Live On Coliru
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/thread/synchronized_value.hpp>
#include <iostream>
boost::asio::io_service io_service;
struct state {
int i = 0;
int j = 0;
};
boost::synchronized_value<state> shared_state;
struct TimerChain {
boost::asio::io_service::strand _strand;
boost::asio::deadline_timer _timer;
TimerChain() : _strand{io_service}, _timer{io_service} {
_timer.expires_from_now(boost::posix_time::milliseconds(50));
resume();
}
void resume() {
_timer.async_wait(_strand.wrap(boost::bind(&TimerChain::test_timer, this, _1)));
};
void stop() { // thread safe
_strand.post([this] { _timer.cancel(); });
}
void test_timer(boost::system::error_code ec)
{
if (ec != boost::asio::error::operation_aborted) {
{
auto state = shared_state.synchronize();
if (state->i++ == 10) {
state->j = state->i * 10;
}
}
// continue indefinitely
_timer.expires_at(_timer.expires_at() + boost::posix_time::milliseconds(50));
resume();
}
}
};
int main()
{
boost::thread_group workers;
TimerChain timer1;
TimerChain timer2;
for (int i = 0; i < 5; i++){
workers.create_thread([] { io_service.run(); });
}
boost::this_thread::sleep_for(boost::chrono::seconds(10));
timer1.stop();
timer2.stop();
workers.join_all();
auto state = shared_state.synchronize();
std::cout << "i = " << state->i << std::endl;
std::cout << "j = " << state->j << std::endl;
}
打印
i = 400
j = 110
¹(或使用旧名称 boost::asio::io_service
)
² 在这方面,生命周期突变不被视为成员操作(即使对于线程安全对象,您也必须手动同步共享对象的构造/销毁)
关于c++ - 使用 boost::asio 时是否需要实现阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507883/