Timers and Asynchronous I/O
This section is the most important one in the entire Boost.Asio tutorial. Serial port, TCP, and UDP asynchronous models are similar to timers: you first register the asynchronous operation, and then
io_context.run()drives the callback execution.
All asynchronous callbacks in this section use std::bind, and do not use lambdas for now.
Example 1: Writing a synchronous timer in an ordinary main()
program objective
First, write the simplest blocking timer: after the program starts, immediately print a sentence, then block for 2 seconds, and then print a final message.
Full code
#include <boost/asio.hpp>
#include <chrono>
#include <print>
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer(io, std::chrono::seconds(2));
std::println("程序开始:准备等待 2 秒");
// 同步等待会阻塞当前线程,时间没到之前不会继续往下执行。
timer.wait();
std::println("2 秒到了:timer.wait() 返回");
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
程序开始:准备等待 2 秒
After waiting about 2 seconds:
2 秒到了:timer.wait() 返回
请提供您要翻译的简体中文 Markdown 片段。
程序开始:准备等待 2 秒
2 秒到了:timer.wait() 返回
Points to note for this example
This program does not demonstrate "asynchronous" behavior because timer.wait() directly blocks the current thread.
In other words, the program is stuck here:
timer.wait();
The next line will not execute until 2 seconds have passed.
Key Function Explanation
boost::asio::io_context io;
Purpose: Create an Asio event loop object.
In the synchronous wait() example, it doesn't seem very prominent; but in the asynchronous version, all asynchronous events rely on it to drive them.
boost::asio::steady_timer timer(io, std::chrono::seconds(2));
Purpose: Create a timer based on a stable clock, set to expire after 2 seconds.
Parameter:
io
Indicates which io_context manages this timer.
std::chrono::seconds(2)
Indicates expiration 2 seconds from the current time.
timer.wait();
Purpose: blocks until the timer expires.
Return value: void.
Features: Simple, but it will block the current thread. In a robot program, if written this way in the main control loop, it can easily hang the entire program.
Example 2: Writing an asynchronous timer in a regular main()
program objective
Rewrite Example 1 using asynchronous syntax:
- Register a 2-second timer;
async_wait()non-blocking;io.run()starts blocking;- The callback function is executed after 2 seconds;
- After no task,
io.run()returns.
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
void on_timer(const boost::system::error_code& ec)
{
if (ec)
{
std::println("定时器被取消,错误信息:{}", ec.message());
return;
}
std::println("回调函数 on_timer:2 秒到了");
}
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer(io, std::chrono::seconds(2));
std::println("main:注册 async_wait");
// 注册异步等待:这一行不会阻塞,回调会在定时器到期后执行。
timer.async_wait(std::bind(on_timer, std::placeholders::_1));
std::println("main:async_wait 已经返回,但回调还没执行");
std::println("main:准备调用 io.run()");
io.run();
std::println("main:io.run() 返回,程序结束");
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
The program immediately outputs:
main:注册 async_wait
main:async_wait 已经返回,但回调还没执行
main:准备调用 io.run()
Then the program gets stuck at:
io.run();
Wait about 2 seconds, then output:
回调函数 on_timer:2 秒到了
main:io.run() 返回,程序结束
请提供您要翻译的简体中文 Markdown 片段。
main:注册 async_wait
main:async_wait 已经返回,但回调还没执行
main:准备调用 io.run()
回调函数 on_timer:2 秒到了
main:io.run() 返回,程序结束
Points to note for this example
async_wait() does not wait for 2 seconds. It simply registers the event of "execute callback after 2 seconds" into io_context.
What truly awaits:
io.run();
So don't interpret async_wait() as an "asynchronous version of wait." More precisely:
async_wait() = 注册任务
io.run() = 执行事件循环
on_timer() = 任务完成后的回调
std::bind Description
This line of code:
timer.async_wait(std::bind(on_timer, std::placeholders::_1));
Meaning:
当 timer 到期后,Boost.Asio 会传入一个 error_code。
这个 error_code 会填到 std::placeholders::_1 的位置。
最后调用 on_timer(ec)。
on_timer's function signature must accept this parameter:
void on_timer(const boost::system::error_code& ec)
Key Function Explanation
timer.async_wait(handler)
Purpose: Register an asynchronous wait operation.
Parameter: a callback function object.
Return value: void.
注意:它不会阻塞等待定时器到期,只负责注册。
io.run()
Purpose: Start the event loop, handle asynchronous tasks and callback functions.
Return value: the number of executed handlers, the type can usually be considered as std::size_t.
In this example, io.run() executed one callback, so the return value is 1. We just didn't print the return value.
Example 3: Writing two asynchronous timers in a common main()
program objective
It's hard to perceive the feeling of asynchronous scheduling with just one timer, so this time we'll write two timers:
timer1expires in 1 second;timer2expires in 3 seconds;- Both timers are in the same
io_context; io.run()will wait until both tasks are completed before returning.
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
#include <string>
void on_timer(const boost::system::error_code& ec, const std::string& name)
{
if (ec)
{
std::println("{} 被取消:{}", name, ec.message());
return;
}
std::println("{} 到期,执行回调", name);
}
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer1(io, std::chrono::seconds(1));
boost::asio::steady_timer timer2(io, std::chrono::seconds(3));
std::println("main:注册 timer1,1 秒后到期");
// 注册异步等待:这一行不会阻塞,回调会在定时器到期后执行。
timer1.async_wait(std::bind(on_timer,
std::placeholders::_1,
std::string("timer1")));
std::println("main:注册 timer2,3 秒后到期");
timer2.async_wait(std::bind(on_timer,
std::placeholders::_1,
std::string("timer2")));
std::println("main:调用 io.run()");
std::size_t count = io.run();
std::println("main:io.run() 返回,一共执行了 {} 个回调", count);
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
The program immediately outputs:
main:注册 timer1,1 秒后到期
main:注册 timer2,3 秒后到期
main:调用 io.run()
Output in about 1 second:
timer1 到期,执行回调
After about another 2 seconds, i.e., about 3 seconds after program startup, output:
timer2 到期,执行回调
main:io.run() 返回,一共执行了 2 个回调
请提供您要翻译的简体中文 Markdown 片段。
main:注册 timer1,1 秒后到期
main:注册 timer2,3 秒后到期
main:调用 io.run()
timer1 到期,执行回调
timer2 到期,执行回调
main:io.run() 返回,一共执行了 2 个回调
Points to note for this example
Two timers are not two threads.
This example has only one thread, which is the main thread. The callbacks of timer1 and timer2 are both executed in this main thread that calls io.run().
The actual execution order is:
主线程进入 io.run()
等待事件
timer1 先到期 -> 调用 timer1 回调
继续等待事件
timer2 后到期 -> 调用 timer2 回调
没有任务了 -> io.run() 返回
他和std::this_thread::sleep_for()不一样,线程里的睡眠是一个阻塞式延迟,而这里的定时器只是一个事件,类似于中断。
Fixed parameters in std::bind
This sentence:
std::bind(on_timer, std::placeholders::_1, std::string("timer1"))
Equivalent to preparing a function object in advance:
未来 Asio 传入 ec 时,调用 on_timer(ec, "timer1")。
_1 is the error code that will be passed in by Asio in the future.
"timer1" is a parameter that is fixed right now.
Example 4: Writing a repeating timer in a normal main()
program objective
Implement a timer that prints once every 1 second, and ends after printing 5 times.
This example is very similar to a periodic task in a robot, for example:
每 20ms 发送一次速度命令
每 100ms 检查一次下位机心跳
每 1s 打印一次通信状态
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
void repeat_timer(const boost::system::error_code& ec,
boost::asio::steady_timer* timer,
int* count)
{
if (ec)
{
std::println("repeat_timer 被取消:{}", ec.message());
return;
}
++(*count);
std::println("第 {} 次定时器回调", *count);
if (*count < 5)
{
// 重新设置下一次到期时间,并再次注册异步等待,使定时器继续周期执行。
timer->expires_after(std::chrono::seconds(1));
timer->async_wait(std::bind(repeat_timer,
std::placeholders::_1,
timer,
count));
}
else
{
std::println("已经执行 5 次,不再重新注册定时器");
}
}
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer(io, std::chrono::seconds(1));
int count = 0;
std::println("main:注册第 1 次定时器");
// 注册异步等待:这一行不会阻塞,回调会在定时器到期后执行。
timer.async_wait(std::bind(repeat_timer,
std::placeholders::_1,
&timer,
&count));
io.run();
std::println("main:io.run() 返回,程序结束");
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
The program immediately outputs:
main:注册第 1 次定时器
About 1 second later:
第 1 次定时器回调
Then output approximately every 1 second:
第 2 次定时器回调
第 3 次定时器回调
第 4 次定时器回调
第 5 次定时器回调
已经执行 5 次,不再重新注册定时器
main:io.run() 返回,程序结束
请提供您要翻译的简体中文 Markdown 片段。
main:注册第 1 次定时器
第 1 次定时器回调
第 2 次定时器回调
第 3 次定时器回调
第 4 次定时器回调
第 5 次定时器回调
已经执行 5 次,不再重新注册定时器
main:io.run() 返回,程序结束
Points to note for this example
The repeating timer is not inside the while loop sleep.
The asynchronous syntax is:
第一次 async_wait
第 1 次回调里重新设置 expires_after
第 1 次回调里再次 async_wait
第 2 次回调里再次注册
……
That is, “before each callback ends, decide whether to register the next one.”
// 重新设置下一次到期时间,并再次注册异步等待,使定时器继续周期执行。
timer->expires_after(std::chrono::seconds(1));
timer->async_wait(std::bind(repeat_timer,
std::placeholders::_1,
timer,
count));
上面这两行很重要:
timer->expires_after(std::chrono::seconds(1));是把定时器的到期时间重新设置为“从现在开始 1 秒后”。它本身不会注册回调,也不会阻塞线程,只是修改定时器的到期时间。
timer->async_wait(std::bind(repeat_timer,std::placeholders::_1,timer,count));决定了到期以后执行谁。
因此这两行可以理解成:“给下一轮定时器续命”。
boost::asio::steady_timer timer(io, std::chrono::seconds(1));只是把第一次到期时间设成“现在之后 1 秒”。第一次到期以后,如果你不再调用上面这两行,那么定时器的到期时间还是原来的那个时间点,已经过去了。
如果你不用expires_after()设定新的时间,那么直接调用async_wait()会导致回调基本会立刻执行。
Pointer Lifecycle Explanation
In this example, passed:
&timer
&count
This is to allow repeat_timer() to modify the same timer and count.
This way of writing is safe in this example because:
timer 和 count 都是 main() 里的局部变量
main() 会卡在 io.run()
io.run() 返回前,timer 和 count 都不会析构
However, in engineering it is more recommended to encapsulate it into a class; see the next example.
Example 5: Writing a Single Asynchronous Timer in a Class
program objective
Convert Example 2 to a class-encapsulated version.
Class encapsulation is a more common approach in robot projects, for example:
SerialDriver 类
TcpClient 类
UdpReceiver 类
RobotController 类
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
class Printer
{
public:
explicit Printer(boost::asio::io_context& io)
: timer_(io, std::chrono::seconds(2))
{
std::println("Printer 构造:注册 2 秒定时器");
// 注册异步等待:这一行不会阻塞,回调会在定时器到期后执行。
timer_.async_wait(std::bind(&Printer::on_timer,
this,
std::placeholders::_1));
}
private:
void on_timer(const boost::system::error_code& ec)
{
if (ec)
{
std::println("Printer::on_timer 被取消:{}", ec.message());
return;
}
std::println("Printer::on_timer:2 秒到了");
}
private:
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer_;
};
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
Printer printer(io);
std::println("main:准备调用 io.run()");
io.run();
std::println("main:io.run() 返回");
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
The program immediately outputs:
Printer 构造:注册 2 秒定时器
main:准备调用 io.run()
Output in about 2 seconds:
Printer::on_timer:2 秒到了
main:io.run() 返回
请提供您要翻译的简体中文 Markdown 片段。
Printer 构造:注册 2 秒定时器
main:准备调用 io.run()
Printer::on_timer:2 秒到了
main:io.run() 返回
Constructor Initializer List Explanation
I see you've indicated "这段:" but didn't include the Chinese text to translate. Please provide the Chinese Markdown fragment you'd like me to translate into natural American English.
explicit Printer(boost::asio::io_context& io)
: timer_(io, std::chrono::seconds(2))
{
}
What follows the colon is called the "constructor initializer list."
Its role is: directly construct the member variable timer_ before entering the constructor's braces.
Why must it be written this way? Because boost::asio::steady_timer does not have a simple way to default-construct it first and then assign a value. It needs to know which io_context it belongs to at construction time.
Member function binding description
This sentence:
timer_.async_wait(std::bind(&Printer::on_timer,
this,
std::placeholders::_1));
The meaning is:
定时器到期后,调用 this->on_timer(ec)。
Why write &Printer::on_timer?
Because on_timer is a member function, not a regular global function. Member functions must depend on an object to be called.
Why pass this?
Because this represents the current Printer object.
Common Pitfalls
Do not write as:
std::bind(on_timer, std::placeholders::_1)
Because on_timer is a member function, not a regular function.
Also do not miss this:
std::bind(&Printer::on_timer, std::placeholders::_1)
This way, I don't know which object's on_timer() to call.
Example 6: Writing Two Timers in a Class
program objective
Maintain two timers simultaneously in a class:
timer1_execute after 1 second;timer2_execute after 3 seconds;- Use this example to clearly see that "two asynchronous tasks are not equivalent to two threads."
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
class TwoTimers
{
public:
explicit TwoTimers(boost::asio::io_context& io)
: timer1_(io, std::chrono::seconds(1)),
timer2_(io, std::chrono::seconds(3))
{
std::println("TwoTimers 构造:注册 timer1 和 timer2");
// 注册异步等待:这一行不会阻塞,回调会在定时器到期后执行。
timer1_.async_wait(std::bind(&TwoTimers::on_timer1,
this,
std::placeholders::_1));
timer2_.async_wait(std::bind(&TwoTimers::on_timer2,
this,
std::placeholders::_1));
}
private:
void on_timer1(const boost::system::error_code& ec)
{
if (ec)
{
std::println("timer1 取消:{}", ec.message());
return;
}
std::println("timer1:1 秒到了");
}
void on_timer2(const boost::system::error_code& ec)
{
if (ec)
{
std::println("timer2 取消:{}", ec.message());
return;
}
std::println("timer2:3 秒到了");
}
private:
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer1_;
boost::asio::steady_timer timer2_;
};
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
TwoTimers app(io);
std::println("main:调用 io.run()");
io.run();
std::println("main:两个定时器都执行完,io.run() 返回");
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
The program immediately outputs:
TwoTimers 构造:注册 timer1 和 timer2
main:调用 io.run()
About 1 second later:
timer1:1 秒到了
After about 3 seconds:
timer2:3 秒到了
main:两个定时器都执行完,io.run() 返回
请提供您要翻译的简体中文 Markdown 片段。
TwoTimers 构造:注册 timer1 和 timer2
main:调用 io.run()
timer1:1 秒到了
timer2:3 秒到了
main:两个定时器都执行完,io.run() 返回
Points to note for this example
timer1_ and timer2_ are two asynchronous tasks, but this example still has only one thread.
Because only the main thread called:
io.run();
So both callbacks are executed in the main thread and will not run in parallel.
Example 7: Two threads run the same io_context simultaneously.
program objective
This time, let both threads call io.run() and observe that the callback may be executed by different threads.
This example is used to understand programs like the official Timer.5:
多个线程 run 同一个 io_context
回调函数可能分配给任意一个正在 run 的线程执行
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
#include <string>
#include <thread>
void print_timer(const boost::system::error_code& ec, const std::string& name)
{
if (ec)
{
std::println("{} 取消:{}", name, ec.message());
return;
}
std::println("{} 回调执行,线程 id = {}", name, std::this_thread::get_id());
}
void run_io(boost::asio::io_context* io, const std::string& thread_name)
{
std::println("{} 开始调用 io.run(),线程 id = {}", thread_name, std::this_thread::get_id());
io->run();
std::println("{} 的 io.run() 返回", thread_name);
}
int main()
{
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
// io_context 是 Asio 的事件循环对象,异步任务需要靠它调度。
boost::asio::io_context io;
// 创建定时器,并设置到期时间。
boost::asio::steady_timer timer1(io, std::chrono::seconds(1));
boost::asio::steady_timer timer2(io, std::chrono::seconds(1));
// 注册异步等待:这一行不会阻塞,回调会在定时器到期后执行。
timer1.async_wait(std::bind(print_timer,
std::placeholders::_1,
std::string("timer1")));
timer2.async_wait(std::bind(print_timer,
std::placeholders::_1,
std::string("timer2")));
std::thread t1(std::bind(run_io, &io, std::string("线程1")));
std::thread t2(std::bind(run_io, &io, std::string("线程2")));
t1.join();
t2.join();
std::println("main:两个线程都结束");
return 0;
}
Running Results: See below for “Execution Output and Timeline”; specific times and sequences may vary slightly with the environment if the example involves timers, threads, networks, or external devices.
Execution output and chronological order
After the program starts, two threads output almost immediately:
线程1 开始调用 io.run(),线程 id = 140000000000001
线程2 开始调用 io.run(),线程 id = 140000000000002
After about 1 second, both timers expire, and the output might be similar:
timer1 回调执行,线程 id = 140000000000001
timer2 回调执行,线程 id = 140000000000002
线程1 的 io.run() 返回
线程2 的 io.run() 返回
main:两个线程都结束
也不一定哪个定时器的回调由哪个线程执行,这是不确定的。
It is also possible that both callbacks are executed by the same thread. Thread scheduling does not guarantee fixed behavior.
Points to note for this example
这个示例的重点是:
谁调用 io.run(),谁就有可能执行回调函数。
It is not that timer1 is permanently assigned to thread 1, and timer2 is permanently assigned to thread 2.
std::thread in std::bind
This sentence:
std::thread t1(std::bind(run_io, &io, std::string("线程1")));
It means to create a thread and execute in the new thread:
run_io(&io, "线程1");
There is also no lambda used here.
Example 8: Using strand in Multithreading to Avoid Callback Concurrency
program objective
如果只有一个线程执行:
io.run();
那么 io_context 中的 handler 自然只能一个接一个执行。
但是如果有多个线程同时执行同一个:
io.run();
For example:
线程1 → io.run()
线程2 → io.run()
那么 io_context 中不同的 handler 就可能被不同线程同时取走并执行。
例如两个定时器同时到期:
线程1 → timer1 的 handler
线程2 → timer2 的 handler
如果这两个 handler 都修改同一个普通成员变量:
int count_;
就可能出现:
线程1:++count_
线程2:++count_
同时执行,从而产生数据竞争。
Boost.Asio 提供的:
strand
就是用来解决这种 handler 并发执行 问题的。
可以先记住最核心的一句话:
绑定到同一个
strand的 handler,不会彼此并发执行。
也就是说,即使:
多个线程同时运行 io_context
同一个 strand 中的 handler 仍然只能:
一个执行完
↓
另一个再执行
Full code
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <functional>
#include <print>
#include <thread>
class StrandCounter
{
public:
explicit StrandCounter(boost::asio::io_context& io)
: strand_(boost::asio::make_strand(io)),
timer1_(io, std::chrono::seconds(1)),
timer2_(io, std::chrono::seconds(1)),
count_(0)
{
// timer1 到期后执行的 handler,
// 通过 bind_executor() 绑定到 strand_。
timer1_.async_wait(
boost::asio::bind_executor(
strand_,
std::bind(
&StrandCounter::on_timer,
this,
std::placeholders::_1,
1)));
// timer2 的 handler 也绑定到同一个 strand_。
timer2_.async_wait(
boost::asio::bind_executor(
strand_,
std::bind(
&StrandCounter::on_timer,
this,
std::placeholders::_1,
2)));
}
private:
void on_timer(
const boost::system::error_code& ec,
int id)
{
if (ec)
{
std::println(
"timer{} 取消:{}",
id,
ec.message());
return;
}
++count_;
std::println(
"timer{} 回调执行,count = {},线程 id = {}",
id,
count_,
std::this_thread::get_id());
}
private:
boost::asio::strand<
boost::asio::io_context::executor_type>
strand_;
boost::asio::steady_timer timer1_;
boost::asio::steady_timer timer2_;
int count_;
};
void run_io(
boost::asio::io_context* io,
const std::string& name)
{
std::println(
"{} 开始 run,线程 id = {}",
name,
std::this_thread::get_id());
io->run();
std::println("{} run 返回", name);
}
int main()
{
boost::asio::io_context io;
StrandCounter counter(io);
std::thread t1(
std::bind(
run_io,
&io,
std::string("线程1")));
std::thread t2(
std::bind(
run_io,
&io,
std::string("线程2")));
t1.join();
t2.join();
std::println("main:结束");
return 0;
}
如果没有 strand 会发生什么
假设我们不使用:
boost::asio::bind_executor(strand_, handler);
而是直接:
timer1_.async_wait(
std::bind(
&StrandCounter::on_timer,
this,
std::placeholders::_1,
1));
timer2_.async_wait(
std::bind(
&StrandCounter::on_timer,
this,
std::placeholders::_1,
2));
同时有两个线程:
线程1 → io.run()
线程2 → io.run()
那么当两个 timer 都到期以后,完全可能出现:
线程1
↓
取到 timer1 handler
↓
进入 on_timer()
线程2
↓
取到 timer2 handler
↓
同时进入 on_timer()
That is: if the communication parameters (like baud rate) set in the microcontroller program are not consistent with those configured in the serial port software on the PC, the communication between the microcontroller and the computer will fail.
时间 ─────────────────────→
线程1: [ timer1 handler ]
线程2: [ timer2 handler ]
↑
发生重叠
两个 handler 里面都有:
++count_;
而:
int count_;
只是普通 int。
所以两个线程同时修改它就会产生data race。
加上 strand 后发生什么
我们先创建:
strand_(boost::asio::make_strand(io))
可以先把它理解成:
在这个
io_context上额外建立一条“串行执行通道”。
然后把两个 handler 都绑定到:
strand_
For example:
boost::asio::bind_executor(
strand_,
handler);
此时:
timer1 handler ──┐
├── 同一个 strand_
timer2 handler ──┘
于是 strand 会保证:
timer1 handler
和
timer2 handler
不会同时执行。
可能是:
线程1:
timer1 handler 开始
↓
++count_
↓
timer1 handler 结束
线程2:
timer2 handler 开始
↓
++count_
↓
timer2 handler 结束
也可能反过来:
线程2:
timer2 handler
然后
线程1:
timer1 handler
但不会出现两个 handler 的执行时间发生重叠。
可以画成:
时间 ─────────────────────────→
线程1: [ timer1 handler ]
线程2: [ timer2 handler ]
或者:
时间 ─────────────────────────→
线程2: [ timer2 handler ]
线程1: [ timer1 handler ]
但不会:
时间 ─────────────────────────→
线程1: [ timer1 handler ]
线程2: [ timer2 handler ]
↑
同时执行
strand 不是“固定线程”
这是理解 strand 最重要的一点之一。
strand 并不是说:
所有绑定到 strand 的 handler
永远都在线程1执行
例如完全可能:
timer1 handler
→ 在线程1执行
timer2 handler
→ 在线程2执行
只要它们:
不同时执行
就是允许的。
So:
strand
≠ 指定一个固定线程
but rather:
strand
= 保证一组 handler 串行执行
换句话说:
strand 管的是“执行时间不能重叠”,不是“必须在哪个线程上执行”。
strand 也不是新的线程
strand 自己不会:
创建一个线程
它仍然依赖:
io.run();
的那些线程来真正执行 handler。
本例中真正执行 handler 的仍然只有:
线程1
线程2
strand 做的只是:
控制同一组 handler 的执行关系
可以理解成:
io_context
↓
┌──────┴──────┐
线程1 线程2
\ /
\ /
strand
↓
handler A
handler B
handler C
handler 仍然由执行 io.run() 的线程来运行,只是 strand 不允许属于自己的两个 handler 同时运行。
为什么这里的 count_ 可以不用 mutex
本例中:
++count_;
只会在:
on_timer()
中执行。
而两个 on_timer() 对应的 handler:
timer1 handler
timer2 handler
都绑定到了同一个:
strand_
所以它们不会并发执行。
于是:
++count_;
也不会被两个线程同时执行。
因此这里不需要再写:
std::mutex mutex_;
std::scoped_lock lock(mutex_);
++count_;
strand 已经通过:
串行化 handler
避免了这里的并发访问。
但 strand 不会自动保护整个对象
这一点也非常重要。
不能因为类里面有:
strand_
就认为:
StrandCounter 整个对象自动线程安全
strand 只能保证:
经过这个 strand 调度的 handler 彼此不并发。
例如本例:
timer1 handler
→ strand_
timer2 handler
→ strand_
所以它们访问:
count_
是安全的。
但如果另外有一个线程直接修改:
count_;
或者另一个没有绑定 strand_ 的 handler 修改:
count_;
那么 strand 管不到它。
For example:
timer1 handler
→ strand_
→ 修改 count_
另一个普通线程
→ 直接修改 count_
这两个还是可能并发。
所以使用 strand 保护某份状态时,需要保证:
所有可能并发访问这份状态的相关操作,都遵守同一个 strand 的串行化规则。
bind_executor() 是干什么的
I see you've indicated "这段:" but didn't include the Chinese text to translate. Please provide the Chinese Markdown fragment you'd like me to translate into natural American English.
boost::asio::bind_executor(
strand_,
handler);
可以理解成:
把这个 handler 的执行器绑定成
strand_。
For example:
timer1_.async_wait(
boost::asio::bind_executor(
strand_,
std::bind(
&StrandCounter::on_timer,
this,
std::placeholders::_1,
1)));
原本可以理解成:
timer1 到期
↓
handler 交给 io_context
↓
某个正在 run() 的线程执行
加入 strand 后变成:
timer1 到期
↓
handler 要经过 strand_
↓
strand_ 保证它不会和
同一个 strand 中的其他 handler 并发
↓
再由某个正在 run() 的线程执行
So:
bind_executor(strand_, handler)
最直观的理解就是:
让这个 handler 遵守
strand_的串行执行规则。
Execution output and chronological order
程序启动以后:
线程1 开始 run,线程 id = 140000000000001
线程2 开始 run,线程 id = 140000000000002
两个线程此时都在:
io->run();
中等待和执行 Asio 的事件。
About 1 second later:
timer1
timer2
都到期。
可能输出:
timer1 回调执行,count = 1,线程 id = 140000000000001
timer2 回调执行,count = 2,线程 id = 140000000000002
线程1 run 返回
线程2 run 返回
main:结束
也可能:
timer2 回调执行,count = 1,线程 id = 140000000000002
timer1 回调执行,count = 2,线程 id = 140000000000001
这些都正常。
因为 strand 不保证:
timer1 一定先执行
也不保证:
timer1 一定在线程1
timer2 一定在线程2
strand 真正保证的是:
两个绑定到同一个 strand 的 handler 不会同时执行。
strand 和 mutex 的思路有什么不同
如果不用 strand,也可以自己:
std::mutex mutex_;
然后:
void on_timer(...)
{
std::scoped_lock lock(mutex_);
++count_;
}
也可以避免数据竞争。
两种思路分别是:
mutex
→ handler 可以同时开始执行
→ 但访问共享状态时竞争锁
而:
strand
→ 从 handler 调度层面就不让它们并发执行
所以在 Boost.Asio 中,如果一组异步 handler:
本来就应该按串行方式处理同一个对象状态
strand 往往是一种很自然的设计。
For example:
串口读回调
串口写完成回调
定时器回调
连接状态回调
如果它们都操作同一个连接对象的内部状态,就可以让这些 handler 统一经过同一个 strand。
Summary:
所以 mutex 很适合:一个大函数里面,只有很小一块共享数据需要保护。
而 strand 更适合:一个对象的一系列异步事件,本来就应该一个一个处理。
本示例最重要的结论
如果一个 io_context 只有一个线程调用:
io.run();
那么 handler 本身不会并发执行。
但如果:
多个线程
↓
同时 io.run()
那么不同 handler 就可能:
在不同线程上同时执行
这时:
strand
可以把某一组 handler 串行化。
最终可以记成:
多个线程 run(io_context)
↓
没有 strand
不同 handler
可能同时执行
↓
访问共享状态时
可能产生 data race
使用同一个 strand:
多个线程 run(io_context)
↓
handler 可以由不同线程执行
↓
但是同一个 strand 中的 handler
不会并发执行
↓
相关状态访问被串行化
所以一句话记住:
strand是 Boost.Asio 提供的 handler 串行化机制:它不固定线程,也不创建线程,只保证绑定到同一个 strand 的 handler 不会彼此并发执行。
Section Summary
You should now remember:
timer.wait()is synchronous blocking.timer.async_wait()registers an asynchronous task and does not block.io.run()is the entry point for the event loop.- A thread
run(), callbacks are executed sequentially within this thread. - Multiple threads
run(), callbacks may be executed by different threads. - When multiple threads share data, use
strandto avoid concurrent callbacks. - The standard syntax for binding a member function in a class is:
std::bind(&ClassName::member_function,
this,
std::placeholders::_1,
std::placeholders::_2)