且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

try_lock在互斥锁上的效率如何?

更新时间:2023-10-26 16:39:34

互斥体是独立于任何实现的逻辑构造.因此,对互斥锁的操作既没有效率也没有效率,它们的定义很简单.

A mutex is a logical construction that is independent of any implementation. Operations on mutexes therefore are neither efficient nor inefficient - they are simply defined.

因此,您的问题类似于询问汽车的效率如何?",而没有提及您可能在谈论哪种汽车.

Your question is therefore akin to asking "How efficient is a car?", without reference to what kind of car you might be talking about.

我可以在现实世界中使用烟雾信号,信鸽或铅笔和纸来实现互斥.我也可以在计算机上实现它们.我可以在Cray 1,Intel Core 2 Duo或地下室486上通过某些操作来实现互斥锁.我可以在硬件中实现它们.我可以在操作系统内核或用户空间中的软件中实现它们,也可以使用两者的某种组合来实现它们.我可能会使用保证在关键部分无冲突的无锁算法来模拟互斥锁(但不实现它们).

I could implement mutexes in the real world with smoke signals, carrier pigeons or a pencil and paper. I could also implement them on a computer. I could implement a mutex with certain operations on a Cray 1, on an Intel Core 2 Duo, or on the 486 in my basement. I could implement them in hardware. I could implement them in software in the operating system kernel, or in userspace, or using some combination of the two. I might simulate mutexes (but not implement them) using lock-free algorithms that are guaranteed conflict-free within a critical section.

您的后续编辑对情况无济于事. 使用低级语言(例如C或其他语言)"几乎是无关紧要的,因为那时我们正要评估语言的实现性能,这充其量只是一个滑坡. "[p] rom pthread或本机系统库提供的任何内容"同样无济于事,因为正如我说的那样,可以通过多种方法在不同环境中实现互斥锁,甚至无法做一个有用的比较.

Your subsequent edits don't help the situation. "In a low level language (like C or whatever)" is mostly irrelevant, because then we're into measuring language implementation performance, and that's a slippery slope at best. "[F]rom pthread or whatever the native system library provides" is similarly unhelpful, because as I said, there are so many ways that one could implement mutexes in different environments that it's not even a useful comparison to make.

这就是为什么您的问题无法回答的原因.

This is why your question is unanswerable.