gpt4 book ai didi

multithreading - 一个条件变量,多个互斥体

转载 作者:行者123 更新时间:2023-12-01 18:59:04 24 4
gpt4 key购买 nike

我正在看Operating system course part 2 lecture 2 video 17 。在本次讲座中,她提到条件变量的数据结构包含互斥引用等待线程列表

我想知道是否可以对不同的互斥体使用相同的条件?

例如:我有 2 个等待语句

  1. 等待(互斥体1,condition_A)
  2. wait(mutex2, condition_A)//条件相同

如果上述问题的答案是肯定的,那么这两条语句会创建两个还是一个条件变量?注意:讲座只提到了一个互斥体引用。

最佳答案

我想这取决于实现。

POSIX 说:

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. Once all waiting threads have been unblocked (as by the pthread_cond_broadcast() operation), the next wait operation on that condition variable shall form a new dynamic binding with the mutex specified by that wait operation.

因此,您可以使用不同的互斥体使用相同的条件变量,但不能同时使用。

关于 C++,cppreference.com说:

Calling this function if lock.mutex() is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior.

所以它似乎与 POSIX 条件变量有相同的要求。

关于multithreading - 一个条件变量,多个互斥体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46461509/

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