gpt4 book ai didi

multithreading - pthread_cond_wait 在等待时自动原子地解锁互斥锁

转载 作者:行者123 更新时间:2023-12-03 12:52:42 26 4
gpt4 key购买 nike

从这里:https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal

Note that the pthread_cond_wait routine will automatically and atomically unlock mutex while it waits.



以下子代码来自同一链接(由我格式化):
pthread_mutex_lock(&count_mutex);

while (count<COUNT_LIMIT)
{
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\n", my_id, count);
}

pthread_mutex_unlock(&count_mutex);

问题:
当它说 pthread_cond_wait等待时会自动解锁互斥锁, 那我们为什么要显式指定函数pthread_mutex_unlock在上面代码的末尾?

我错过了什么?

最佳答案

pthread_cond_wait解锁它再次持有锁。例如,假设您绕过循环两次,您会在互斥体上获得以下锁定/解锁序列:

lock

# Around loop twice:
wait (unlock)
awaken (holding lock)
wait (unlock)
awaken (holding lock)

# loop done, still holding lock

unlock

如果您没有最后一次解锁,那么下次其他人想要获得锁时,您将陷入死锁。

关于multithreading - pthread_cond_wait 在等待时自动原子地解锁互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062701/

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