c++ - 关于无锁编程的一些疑惑

标签 c++ c assembly lock-free

<分区>

嗨伙计们,
首先抱歉,这将是一个中等长度的帖子。所以,请耐心阅读。

在这里,我将记下我在浏览一些有关无锁编程的文章时学到的一些概念,并提出我对这些知识的疑惑。
此外,讨论是关于 *NIX 多处理器平台的。

首先说“LOCKLESS = BLOCKLESS”,因为据说线程系统作为一个整体取得进展,因为 CAS/DCAS 只有在某些线程取得进展时才会失败。
因此,我们可以说,在互斥量阻塞的情况下,我们正在旋转/等待一个条件(例如 CAS while 循环)。

Quest1 > How would spinning on a while loop be more efficient than blocking on a
mutex ?
Quest2 > A good design employing mutexes also ensure that system progresses, so
isnt that BLOCKLESS too by definition?

作为问题 1 的答案,有人会争辩说,阻塞可能会进入内核等待状态,并且可能会有代价高昂的上下文切换。任何进一步的澄清将不胜感激。

好吧,假设在得到前 2 个问题的答案后,我会确信当要完成的原子操作不是很大/不耗时时,无锁确实是快速和实时的。< br/>

Quest3 > So, isnt lock-free something like spinlock ? If yes, why cant we use 
pthread spin lock ?

继续前进,在网络上可用的大多数文献中,人们会看到这样一种原子操作的实现:

__asm__ __volatile__("lock\nxadd" X " %0,%1"                                               
                          : "=r"(result),"=m"(*(T *)i_pAddress)                                            
                          : "0"(i_addValue)                                                              
                          : "memory");  // What does this mean ? Memory Fencing ?
Quest4 > Does ":memory" in the above assemble mean memory fencing ? If yes, 
doesnt that take around 100 cycles to implement ?
Quest5 > Doesnt the lock instruction here assert that the operation is being
done on a shared resource, thus other threads are blocking here ?
As far as I know
this question is not valid for the more or less recent Intel multi proc arch
as the locking is done on cache lines.

提前致谢。

最佳答案

问题太多了!

How would spinning on a while loop be more efficient than blocking on a mutex ?

如果资源基本上没有竞争,平均而言您不必旋转很长时间。这可能比使用互斥体更便宜。

A good design employing mutexes also ensure that system progresses, so isn't that BLOCKLESS too by definition?

这可能对等待的线程更公平。如果在等待资源时自旋,“倒霉”的线程可能需要等待很长时间。

So, isn't lock-free something like spinlock ? If yes, why can't we use pthread spin lock ?

如果您对如何使算法无锁有一个好主意,您可能根本不需要自旋。

Does ":memory" in the above assemble mean memory fencing ? If yes, doesn't that take around 100 cycles to implement ?

是的,系统上的内存防护需要它。同步大量 CPU 缓存会花费很长时间(可能超过 100 个时钟)。另一方面,自旋锁或互斥锁也需要内存栅栏才能正常工作。

Doesn't the lock instruction here assert that the operation is being done on a shared resource, thus other threads are blocking here?

这是一种不同类型的阻塞,可能是在硬件级别。如果其他线程需要您刚刚更新的数据,他们需要等待它在他们的 CPU 上可用。

关于c++ - 关于无锁编程的一些疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10426420/

相关文章:

C 结构、函数指针和头文件问题(不确定是哪个原因)

gcc - 尝试使用具有多个替代约束的内联汇编在 amd64 中实现 128 位添加

assembly - 在MIPS中读取文件时,它读取最后一行两次

assembly - MIPS计算跳转指令的机器编码

c++ - 使用模板特化拆分可变参数包

c - 递增指向数组的指针

c++ - 从函数中通过引用返回 Eigen::VectorXd

C pthread : Multiple Threads but only ONE thread is used

c++ - 是否可以在派生类中使用复制构造函数而不使用基复制构造函数?

c++ - 对于简单的 StereoBM 算法,为什么我的代码比 opencv 慢得多?