不知何故,这个问题的后续行动。我只是想知道是否可以使用std::mutex
由 a 处理的 in 函数boost::asio:io_service
?股线的使用有点不切实际。根据我在boost 参考中找到的内容,我会说没关系。既然它指出
异步完成处理程序只会从当前正在调用 io_service::run() 的线程中调用。
所以 boost 创建的其他线程不应该干扰。我做对了吗?
正如其他人所指出的,std::mutex
其他锁定机制可以在处理程序中使用。但是,两者之间存在根本区别:
strand
用于消除处理程序之间的争用,从而消除处理程序之间的竞争条件。如果整个处理程序是由于与其他处理程序的潜在竞争条件而同步的,而不是线程池外部的线程,那么我想强调外部机制和boost::asio::strand
.
考虑以下场景:
A
和B
将在同一个互斥锁上同步。C
不需要同步。A
,B
和C
发布到io_service
.A
并被B
调用。由于外部同步,线程池现在已耗尽,因为两个线程都在使用。不幸的是,其中一个线程在资源上被阻塞,导致不需要同步的处理程序,例如C
,坐在队列中。
If a strand is used for synchronization in this scenario, then this instance of starvation would not have occurred. A strand
maintains its own handler queue, and guarantees that only one of its handlers is in the io_service
, resulting in handlers being synchronized before being placed into the io_service
. In the scenario, if A
and B
are posted into the strand
, then the strand
will post A
into the io_service
. This would result in A
and C
being in the io_service
, allowing C
to run concurrently while B
remains in the strand
's queue waiting for A
to complete.
Also, there are use cases where both of these forms of synchronization can be used together. For example, consider the case where resources are shared with a thread running outside of the threadpool. A mutex would still be required by threads internal and external to the threadpool. However, a strand
could be used to remove the contention for the mutex between threads internal to the threadpool.
是的,使用std::mutex
处理程序的内部非常好。strand
毕竟,A只是一个带有互斥锁的队列。
boost
只是从它的角度调用回调。这个回调与 没有关系boost
,所以boost
不在乎你在回调中做了什么。因此,锁定(使用您想要的任何锁定库)非常好。
Mutex inside completion handler can block thread execution. In that case you need more io_service
threads than boost::thread::hardware_concurrency()
to load CPU for 100%. It increases thread switching overhead.