asio strand

io_service不能保证线程安全 
strand提供串行执行, 能够保证线程安全, 同时被post或dispatch的方法, 不会被并发的执行.

`asio::io_context::strand::post` 和 `asio::steady_timer::expires_after` 都是 Boost.Asio 库中的功能。 `asio::io_context::strand::post` 可以将一个函数或者 Lambda 表达式提交到指定的 `strand` 上执行。`strand` 是 Boost.Asio 中用于处理多个线程访问同一个 `io_context` 的线程安全机制。 例如: ```cpp asio::io_context io_context; asio::io_context::strand strand(io_context); void handler1() { std::cout << "handler1: " << std::this_thread::get_id() << std::endl; } void handler2() { std::cout << "handler2: " << std::this_thread::get_id() << std::endl; } void post_handlers() { strand.post(handler1); strand.post(handler2); } std::thread t1(post_handlers); std::thread t2(post_handlers); io_context.run(); t1.join(); t2.join(); ``` 在上面的代码中,我们创建了一个 `io_context` 和一个 `strand`。然后我们创建了两个函数 `handler1` 和 `handler2`,并将它们都提交到了 `strand` 上执行。接下来,我们创建了两个线程分别执行 `post_handlers` 函数,这个函数会将 `handler1` 和 `handler2` 提交到 `strand` 上。最后我们启动了 `io_context` 的事件循环并等待两个线程执行完毕。 `asio::steady_timer::expires_after` 是一个定时器的功能,可以设置定时器在一定时间后超时。例如: ```cpp asio::io_context io_context; asio::steady_timer timer(io_context); void handler(const boost::system::error_code& error) { if (!error) { std::cout << "timer expired" << std::endl; } } void start_timer() { timer.expires_after(std::chrono::seconds(1)); timer.async_wait(handler); } start_timer(); io_context.run(); ``` 在上面的代码中,我们创建了一个 `io_context` 和一个 `steady_timer`。然后我们定义了一个回调函数 `handler`,当定时器超时时会被调用。接下来,我们创建了一个函数 `start_timer`,它会设置定时器超时时间为 1 秒,并异步等待定时器超时。最后我们启动了 `io_context` 的事件循环,当定时器超时时,`handler` 函数会被调用。 需要注意的是,`asio::steady_timer::expires_after` 的时间是相对时间,而不是绝对时间。如果需要设置绝对时间,可以使用 `asio::steady_timer::expires_at`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金士顿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值