gpt4 book ai didi

c - while (pthread_mutex_trylock(mutex)) 有什么意义

转载 作者:太空狗 更新时间:2023-10-29 11:19:23 28 4
gpt4 key购买 nike

最近看了memcached的源码,在文件 memcached.h 中。我找到了这段代码:

static inline int mutex_lock(pthread_mutex_t *mutex)
{
while (pthread_mutex_trylock(mutex));
return 0;
}

我只是想知道为什么不直接使用pthread_mutex_lock。上面的代码有什么好处?

pthread_mutex_trylock 之后休眠 1 或 2 秒 看起来更合理,因为它不会浪费 CPU 资源。

有什么想法吗?

谢谢。

最佳答案

这本质上是一个自旋锁。这个想法是让线程避免在内核中阻塞,这可能是一种损害线程效率的操作。

这种自旋锁只有在锁的争用率相当低和/或持有时间很短的情况下才有意义。显然,如果您在 while 循环中进行一系列迭代,这也会降低效率。

此外,我相信 libc 通常会在阻塞之前稍微旋转一下来实现 pthread_mutex_lock(),但我必须深入挖掘(可能难以阅读)源代码来验证.

另一点 - 如果在单核系统上运行,这将是非常愚蠢的代码,但它们正在消失。

关于c - while (pthread_mutex_trylock(mutex)) 有什么意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21179127/

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