gpt4 book ai didi

c++ - std::timed_mutex::try_lock* 虚假地失败

转载 作者:可可西里 更新时间:2023-11-01 15:38:52 27 4
gpt4 key购买 nike

try_lock* 是指 try_lock()try_lock_for()try_lock_until()。根据cppreference ,这三种方法都可能会虚假地失败。以下引用自 try_lock_for()

的描述

As with try_lock(), this function is allowed to fail spuriously and return false even if the mutex was not locked by any other thread at some point during timeout_duration.

我知道 std::condition_variable 可能会发生虚假唤醒及其背后的基本原理。但是,互斥量是怎么回事?

最佳答案

根据:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3209.htm

On the other hand, there are strong reasons to require that programs be written to tolerate spurious try_lock() failures:

  1. As pointed out in Boehm, Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 08, enforcing sequential consistency for data-race-free programs without spurious try_lock() failures requires significantly stronger memory ordering for lock() operations on try_lock()-compatible mutex types. On some architectures that significantly increases the cost of uncontended mutex acquisitions. This cost appears to greatly outweigh any benefit from prohibiting spurious try_lock() failures.
  2. It allows a user-written try_lock() to fail if, for example, the implementation fails to acquire a low-level lock used to protect the mutex data structure. Or it allows such an operation to be written directly in terms of compare_exchange_weak.
  3. It ensures that client code remains correct when, for example, a debugging thread is introduced that occasionally acquires locks in order to be able to read consistent values from a data structure being checked or examined. Any code that obtains information from try_lock() failure would break with the introduction of another thread that purely locks and reads the data structure.

关于c++ - std::timed_mutex::try_lock* 虚假地失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907999/

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