简体   繁体   English

为什么boost :: mutex使用原子操作和事件而不是关键部分

[英]Why boost::mutex uses atomic operations and events instead of critical sections

According to the answers from this question last versions of boost::mutex uses atomic operations and a Win32 Event for blocking waits instead of critical sections. 根据该问题的答案, boost::mutex最新版本使用原子操作和Win32 Event来阻止等待而不是关键部分。 Why? 为什么? What is the reason behind it? 背后的原因是什么?

I belive that this what you are looking for (from https://www.justsoftwaresolutions.co.uk/articles/implementing_mutexes.html ): 我相信您正在寻找的东西(来自https://www.justsoftwaresolutions.co.uk/articles/implementing_mutexes.html ):

The simplest way to implement a mutex would be to write a wrapper class for one of the native Windows synchronization objects; 实现互斥锁的最简单方法是为一个本机Windows同步对象编写一个包装类。 after all, that's what they're there for. 毕竟,这就是他们的目标。 Unfortunately, they all have their problems. 不幸的是,他们都有自己的问题。 The Mutex, Event and Semaphore are kernel objects, so every synchronization call requires a context switch to the kernel. Mutex,Event和Semaphore是内核对象,因此每个同步调用都需要上下文切换到内核。 This can be rather expensive, especially so when there is no contention. 这可能会相当昂贵,尤其是在没有竞争的情况下。

Boost mutexes are only designed for use within a single process, so the CRITICAL_SECTION looks appealing. Boost互斥锁仅设计用于单个过程,因此CRITICAL_SECTION看起来很有吸引力。 Unfortunately, there are problems with this, too. 不幸的是,这也存在问题。 The first of these is that it requires explicit initialization, which means it cannot reliably be used as part of an object with static storage duration — the standard static-initialization-order problem is compounded by the potential of race conditions, especially if the mutex is used as a local static. 首先,它需要显式初始化,这意味着它不能可靠地用作具有静态存储持续时间的对象的一部分-标准的静态初始化顺序问题由竞争条件的潜在条件加重了,特别是如果互斥量为用作本地静态变量。 On most compilers, dynamic initialization of objects with static storage duration is not thread-safe, so two threads may race to run the initialization, potentially leading to the initialization being run twice, or one thread proceding without waiting for the initialization being run by the other thread to complete. 在大多数编译器上,具有静态存储持续时间的对象的动态初始化不是线程安全的,因此两个线程可能竞相运行该初始化,从而可能导致该初始化运行两次,或者一个线程在不等待初始化运行的情况下运行该线程。其他线程完成。 The second problem is that you can't do a timed wait on a CRITICAL_SECTION, which means we need another solution for a mutex that supports timed waits, anyway. 第二个问题是您不能对CRITICAL_SECTION进行定时等待,这意味着无论如何我们都需要另一种支持定时等待的互斥锁解决方案。

There is also another problem with using CRITICAL_SECTIONs as a high-performance mutex, which is that a thread unlocking the CRITICAL_SECTION will hand-off ownership to a waiting thread. 将CRITICAL_SECTIONs用作高性能互斥锁还有另一个问题,那就是解锁CRITICAL_SECTION的线程会将所有权移交给等待的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM