gpt4 book ai didi

c++ - POSIX 条件变量和互斥量 "competition"

转载 作者:太空狗 更新时间:2023-10-29 21:31:26 30 4
gpt4 key购买 nike

当一个线程等待一个条件变量时,关联的互斥锁被(原子地)释放(解锁)。当该条件变量(由不同的线程)发出信号时,一个(对于信号)或所有(对于广播)等待线程被唤醒,自动重新获取(锁定)互斥量。

如果一个或多个其他线程正在等待获取(锁定)同一个互斥锁,但没有等待相同的条件,会发生什么情况?在其他线程获取(锁定)互斥锁之前,等待条件变量的线程是否保证被唤醒(并因此获取互斥锁),或者其他线程是否可以获取(锁定)互斥锁在等待条件变量的线程之前?

[注意:为清楚起见,对以下示例进行了简化。 Thread_B 并没有真正启动 Thread_C,但 Thread_C 保证不会运行,直到 Thread_B 获得互斥体之后——它不会在 Thread_A 等待条件变量后与 Thread_B 竞争互斥体]

线程_A:

pthread_mutex_lock(&myMutex);
while (!someState) {
pthread_cond_wait(&myCondVar,&myMutex);
}
// do something
pthread_mutex_unlock(&myMutex);

线程_B:

pthread_mutex_lock(&myMutex);
// do other things
someState = true;
// start Thread_C here
pthread_cond_signal(&myCondVar);
pthread_mutex_unlock(&myMutex);

线程_C:

pthread_mutex_lock(&myMutex);
// can I reach this point after Thread_B releases the mutex,
// but before Thread_A re-acquires it after being signaled?

// do things that may interfere with Thread_A...
pthread_mutex_unlock(&myMutex);

编辑:选择下面接受的答案是因为它清楚地表明,无论读者是否同意给出的解释,都存在足够的歧义,唯一安全的假设是受访者的假设。请注意,精通 C++ 标准语言的其他人可能会发现文本完全不含糊......我不属于该组。

最佳答案

与任何其他已在 pthread_mutex_lock() 中阻塞并尝试获取相同的线程相比,从 pthread_cond_[timed]wait() 唤醒时获取互斥锁没有什么特别之处互斥体。

Per the POSIX 7 pthread_cond_signal() documentation (加粗我的):

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked. When each thread unblocked as a result of a pthread_cond_broadcast() or pthread_cond_signal() returns from its call to pthread_cond_wait() or pthread_cond_timedwait(), the thread shall own the mutex with which it called pthread_cond_wait() or pthread_cond_timedwait(). The thread(s) that are unblocked shall contend for the mutex according to the scheduling policy (if applicable), and as if each had called pthread_mutex_lock().

pthread_cond_[timed]wait() 唤醒后获取互斥锁 需要 完全 就好像线程调用了 pthread_mutex_lock()

简而言之,任何线程都可以获得互斥量。

关于c++ - POSIX 条件变量和互斥量 "competition",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139036/

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