boost asio add event while asio.run() in another thread

当在一个线程中调用io_context.run()后,在另一个线程中添加事件,是线程安全的。
这是在stackoverflow中找到的代码,原文如下
void CalculateFib(std::size_t n);

int main()
{
boost::asio::io_service io_service;
boost::optionalboost::asio::io_service::work work = // ‘. 1
boost::in_place(boost::ref(io_service)); // .’

boost::thread_group worker_threads; // -.
for(int x = 0; x < 2; ++x) // :
{ // ‘.
worker_threads.create_thread( // :- 2
boost::bind(&boost::asio::io_service::run, &io_service) // .’
); // :
} // -’

io_service.post(boost::bind(CalculateFib, 3)); // ‘.
io_service.post(boost::bind(CalculateFib, 4)); // :- 3
io_service.post(boost::bind(CalculateFib, 5)); // .’

work = boost::none; // 4
worker_threads.join_all(); // 5
}
At a high-level, the program will create 2 threads that will process the io_service’s event loop (2). This results in a simple thread pool that will calculate Fibonacci numbers (3).

The one major difference between the Question Code and this code is that this code invokes io_service::run() (2) before actual work and handlers are added to the io_service (3). To prevent the io_service::run() from returning immediately, an io_service::work object is created (1). This object prevents the io_service from running out of work; therefore, io_service::run() will not return as a result of no work.

The overall flow is as follows:

Create and add the io_service::work object added to the io_service.
Thread pool created that invokes io_service::run(). These worker threads will not return from io_service because of the io_service::work object.
Add 3 handlers that calculate Fibonacci numbers to the io_service, and return immediately. The worker threads, not the main thread, may start running these handlers immediately.
Delete the io_service::work object.
Wait for worker threads to finish running. This will only occur once all 3 handlers have finished execution, as the io_service neither has handlers nor work.
The code could be written differently, in the same manner as the Original Code, where handlers are added to the io_service, and then the io_service event loop is processed. This removes the need to use io_service::work, and results in the following code:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值