gpt4 book ai didi

c++ - 为什么 boost::mutex 使用原子操作和事件而不是临界区

转载 作者:行者123 更新时间:2023-11-30 03:47:49 28 4
gpt4 key购买 nike

根据this question的回答boost::mutex 的最新版本使用原子操作和 Win32 事件来阻塞等待而不是关键部分。为什么?背后的原因是什么?

最佳答案

我相信这就是您正在寻找的(来自 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; 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. 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. 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.

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.

关于c++ - 为什么 boost::mutex 使用原子操作和事件而不是临界区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498289/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com