gpt4 book ai didi

c - 在 POSIX 中,为什么不能将单个 condvar 与多个互斥量一起使用?

转载 作者:行者123 更新时间:2023-12-04 17:18:52 32 4
gpt4 key购买 nike

当 POSIX 条件变量与多个互斥量一起使用时,为什么行为未定义?

摘自 2018 年版:

When a thread waits on a condition variable, having specified a particular mutex to either the pthread_cond_timedwait() or the pthread_cond_wait() operation, a dynamic binding is formed between that mutex and condition variable that remains in effect as long as at least one thread is blocked on the condition variable. During this time, the effect of an attempt by any thread to wait on that condition variable using a different mutex is undefined

我想这是因为某些特定系统的某种实现细节,所以有人可以证实或反驳它吗?

C11(和 C17)条件变量似乎没有这样的限制,为什么?

最佳答案

C11 (and C17) condition variables don't seem to have such limitation,

我同意 C11 和 C17 似乎没有记录对与 cnd_waitcnd_timedwait 一起使用的互斥量的任何限制。但是,它们确实允许这些函数失败,并且它们可能失败的一个似是而非的原因是指定了与当前等待指定的相同 CV 的另一个线程不同的互斥体。

and why?

我只能推测标准委员会的动机和思考过程。可能成员希望允许没有此类限制的实现,并且他们假设其他实现会简单地行使他们的选择权以在需要时失败。可能这只是一个疏忽。

期望多个线程不会同时等待具有不同互斥体的 CV,这对于条件变量实现来说很普通,也适用于条件变量使用模式。 POSIX 的限制绝不是独一无二的:

  • C++ std::condition_variable 有一个类似于 POSIX 的限制
  • Java 对象的监控器和 java.util.concurrent.locks.Condition 的实现本质上与特定的锁相关联,因此人们甚至不能表达尝试同时使用不同的锁。
  • Python threading.Condition 对象也与特定的锁相关联。

关于c - 在 POSIX 中,为什么不能将单个 condvar 与多个互斥量一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67395086/

32 4 0