asio 多线程无锁串行化

in cn-programming •  6 years ago  (edited)

 单 io_service 多线程模式时 io_service 的典型用法,在这种模式下,多个线程会竞争 io_service,竞争到的线程会得到处理下一个 handler 的机会,通过这种用法,表现为 io_service 会自动的将 io 事件分配给各个线程去处理,并且我们自己的任务也可以通过 io_service.post() 丢给线程们去执行,这相当于我们拥有了一个线程池。 

 io_service 本身是线程安全的,多个线程在竞争 io_service 时会加锁,然而这只是在竞争 io_service 时加锁,在任何一个线程拿到 io_service 并开始执行 handler 后,io_service 的锁会释放交给其他线程继续竞争。所以可以看到,handlers 是多线程并发执行的,在各个 handlers 中如果存在共享的数据,我们仍是需要处理同步问题。

为此 io_service 提供了 strand,strand 可以用来包裹 handlers,被同一个 strand 包裹的 handlers 会串行执行,这样就可以省的我们自己在 handlers 为共享数据加锁了。实际上,当我们只在一个线程上执行 io_service.run() 时,所有的 handlers 也是通过一个 strand 串行执行的,这在 asio 文档中被称为 "implicit strand".  

可以想象,如果我们在多线程单 io_service 的用法下,对所有 handlers 使用同一个 strand 包裹,那么这些 handlers 也将全部串行执行,这将和单线程单 io_service 没有区别,多线程在这种情况下就没有意义了。

另外要注意 strand 是属于某个 io_service 的,也就是说 strand 只能串行化它属于的 io_service 下的 handlers。 

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Hello! Your post has been resteemed and upvoted by @ilovecoding because we love coding! Keep up good work! Consider upvoting this comment to support the @ilovecoding and increase your future rewards! ^_^ Steem On!

Reply !stop to disable the comment. Thanks!