简介
为什么要无锁编程?深入理解无锁编程
- 异步比同步要好
- 非阻塞比阻塞要好,而锁会引起阻塞,线程一直在跑就是正常的cpu调度,阻塞唤醒一次则意味着两次cpu调度,且竞争比较激烈的时候,一次唤醒所有等待锁的线程又会带来阻塞。PS: 加锁还会进入内核态,但单纯执行CAS指令却不会。
加锁会大大拖慢我们的性能。在获取锁过程中,CPU 没有去执行计算的相关指令,而要等待操作系统或者 JVM 来进行锁竞争的裁决。而那些没有拿到锁而被挂起等待的线程,则需要进行上下文切换。这个上下文切换,会把挂起线程的寄存器里的数据放到线程的程序栈里面去。这也意味着,加载到高速缓存里面的数据也失效了,程序就变得更慢了。
从某种意义上来讲,所谓的无锁,仅仅只是颗粒度特别小的“锁”罢了,从代码层面上逐渐降低级别到CPU的指令级别而已,总会在某个层级上付出等待的代价,除非逻辑上彼此完全无关。
《软件架构设计》
实现无锁的几个粒度
- 只有一个线程写,一/多个线程读,仅靠内存屏障即可。PS:内存屏障保证了可见性,支持了有序性。
- 多个线程写,内存屏障 + CAS
基于内存屏障,有了Java中的volatile 关键字,再加上“单线程写” 原则,就有了Java中的Disruptor,其核心就是:一写多读,完全无锁。
Lock-Free Data Structures
Lock-Free Data Structures 要点如下
- In classic lock-based programming, whenever you need to share some data, you need to serialize access to it.
- what’s that “small set of things” that you can do atomically in lock-free programming? In fact, what would be the minimal set of atomic primitives that would allow implementing any lock-free algorithm—if there’s such a set?
- Herlihy (http://www.podc.org/dijkstra/2003.html) proves which primitives are good and which are bad for building lock-free data structures. That brought some seemingly hot hardware architectures to instant obsolescence, while clarifying what synchronization primitives should be implemented in future hardware.
- For example, Herlihy’s paper gave impossiblity results, showing that atomic operations such as test-and-set, swap, fetch-and-add, or even atomic queues (!) are insufficient for properly synchronizing more than two threads.
- On the bright side, Herlihy also gave universality results, proving that some simple constructs are enough for implementing any lock-free algorithm for any number of threads.The simplest and most popular universal primitive, is the compare-and-swap (CAS) operation
- Compiler 和 cpu 经常搞一些 optimizations,这种单线程视角下的优化在多线程环境下是不合时宜的,为此要用 memory barriers 来禁止 Compiler 和 cpu 搞这些小动作。 For purposes here, I assume that the compiler and the hardware don’t introduce funky optimizations (such as eliminating some “redundant” variable reads, a valid optimization under a single-thread assumption). Technically, that’s called a “sequentially consistent” model in which reads and writes are performed and seen in the exact order in which the source code does them. 这里假定代码是什么顺序,实际执行就是什么顺序。
一个无锁的map
- Reads have no locking at all.
- Updates make a copy of the entire map, update the copy, and then try to CAS it with the old map. While the CAS operation does not succeed, the copy/update/CAS process is tried again in a loop.
- Because CAS is limited in how many bytes it can swap, WRRMMap stores the Map as a pointer and not as a direct member of WRRMMap.
代码
// 1st lock-free implementation of WRRMMap
// Works only if you have GC
template <class K, class V>
class WRRMMap {
Map<K, V>* pMap_;
public:
V Lookup (const K& k) {
//Look, ma, no lock
return (*pMap_) [k];
}
void Update(const K& k,
const V& v) {
Map<K, V>* pNew = 0;
do {
Map<K, V>* pOld = pMap_;
delete pNew;
pNew = new Map<K, V>(*pOld);
(*pNew) [k] = v;
} while (!CAS(&pMap_, pOld, pNew));
// DON'T delete pMap_;
}
};
先证明 做到了 哪些primitives 便可以支持 无锁编程 ==> 推动硬件支持 ==> 基于硬件支持实现无锁数据结构与算法。
Lock-Free Programming
-
Problems with Locking
- Deadlock
- Priority inversion,Low-priority processes hold a lock required by a higher priority process
- Kill-tolerance,If threads are killed/crash while holding locks, what happens?
- Async-signal safety,Signal handlers can’t use lock-based primitives
-
Overall performance,Constant struggle between simplicity and efficiency,比如 thread-safe linked list with lots of nodes:
- Lock the whole list for every operation?
- Reader/writer locks?
- Allow locking individual elements of the list?
-
Definition of Lock-free programming
- Thread-safe access to shared data without the use of synchronization primitives such as mutexes
- Possible but not practical in the absence of hardware support 需要硬件支持
-
General Approach to Lock-Free Algorithms
- Designing generalized lock-free algorithms is hard
- Design lock-free data structures instead,Buffer, list, stack, queue, map, deque, snapshot 无锁编程 落实到实处就是使用 无锁的数据结构
Writing Lock-Free Code: A Corrected Queue page1 提到:When writing lock-free code, always keep these essentials well in mind:
-
Key concepts.
- Think in transactions. When writing a lock-free data structure, “to think in transactions” means to make sure that each operation on the data structure is atomic, all-or-nothing with respect to other concurrent operations on that same data. (你当前访问的数据别人也在访问, all-or-nothing)The typical coding pattern to use is to do work off to the side, then “publish” each change to the shared data with a single atomic write or compare-and-swap(一种常用的模式是,你先在临界区外将活儿干完,然后原子的替换掉shared data). Be sure that concurrent writers don’t interfere with each other or with concurrent readers, and pay special attention to any operations that delete or remove data that a concurrent operation might still be using.(删除操作尤其要小心,因为对应的数据可能正在被别人使用)
- Know who owns what data. 下一小节有介绍
-
Key tool. The ordered atomic variable.
An ordered atomic variable is a “lock-free-safe” variable with the following properties(也就是原子性和有序性,作者忽略了有序性) that make it safe to read and write across threads without any explicit locking:
Atomicity. Each individual read and write is guaranteed to be atomic with respect to all other reads and writes of that variable. The variables typically fit into the machine’s native word size, and so are usually pointers (C++), object references (Java, .NET), or integers.
Order. Each read and write is guaranteed to be executed in source code order. Compilers, CPUs, and caches will respect it and not try to optimize these operations the way they routinely distort reads and writes of ordinary variables.
Compare-and-swap (CAS) . There is a special operation you can call using a syntax like variable(cas 作为一种变量操作符的存在).compare_exchange( expectedValue, newValue ) that does the following as an atomic operation: If variable currently has the value expectedValue, it sets the value to newValue and returns true; else returns false. A common use is if(variable.compare_exchange(x,y)), which you should get in the habit of reading as, “if I’m the one who gets to change variable from x to y.”
If you don’t yet have ordered atomic variables yet on your language and platform, you can emulate them by using ordinary but aligned variables whose reads and writes are guaranteed to be naturally atomic, and enforce ordering by using either platform-specific ordered API calls (such as Win32’s InterlockedCompareExchange for compare-and-swap) or platform-specific explicit memory fences/barriers (for example, Linux mb). 如果你使用的编程语言不支持原子和有序性,你该如何模拟呢?
- 使用可对齐的变量类型,其自然支持原子操作
- 使操作有序,可以通过直接的api 或 使用内存屏障
一个常见的套路是“两阶段写入”,在写入数据之前,先加锁申请批量的空闲存储单元(这个申请的过程是需要加锁的,但加一次锁却申请多个连续空间),之后往队列中写入数据的操作就不需要加锁了,写入的性能因此就提高了。参见disruptor 实现原理 剖析Disruptor:为什么会这么快?(一)锁的缺点剖析Disruptor:为什么会这么快?(二)神奇的缓存行填充
Lock-Free Queue
只有一个生产者和消费者
Writing Lock-Free Code: A Corrected Queue
The consumer increments divider to say it has consumed an item. The producer increments last to say it has produced an item, and also lazily cleans up consumed items before the divider.
对于一个队列数据结构
template <typename T>
class LockFreeQueue {
private:
struct Node {
Node( T val ) : value(val), next(nullptr) { }
T value;
Node* next;
};
Node* first; // for producer only
atomic<Node*> divider, last; // shared
生产者代码
void Produce( const T& t ) {
last->next = new Node(t); // add the new item
last = last->next; // publish it
while( first != divider ) { // trim unused nodes
Node* tmp = first;
first = first->next;
delete tmp;
}
}
last->next = new Node(t);
这一句执行完毕时,新的node is not yet shared, 仍然是 producer thread 私有的。直到执行last = last->next;
we write to last to “commit” the update and publish it atomically to the consumer thread.
Finally, the producer performs lazy cleanup of now-unused nodes. Because we always stop before divider, this can’t conflict with anything the consumer might be doing later in the list. 此处producer而不是consumer负责清理节点,一直没有理解到精髓。
消费者代码
bool Consume( T& result ) {
if( divider != last ) { // if queue is nonempty
result = divider->next->value; // C: copy it back
divider = divider->next; // D: publish that we took it
return true; // and report success
}
return false; // else report empty
};
consumer thread 只是读取 last 来判断队列是否为空,if 判断以后,无论last 是否后移,对逻辑操作都没什么影响
多个生产者和消费者
Writing a Generalized Concurrent Queue
对于多个生产者和消费者,如何线程安全?
有锁版本
template <typename T>
struct LowLockQueue {
private:
struct Node {
Node( T* val ) : value(val), next(nullptr) { }
T* value;
atomic<Node*> next;
char pad[CACHE_LINE_SIZE - sizeof(T*)- sizeof(atomic<Node*>)];
};
char pad0[CACHE_LINE_SIZE];
Node* first;
char pad1[CACHE_LINE_SIZE- sizeof(Node*)];
// shared among consumers
atomic<bool> consumerLock;
char pad2[CACHE_LINE_SIZE - sizeof(atomic<bool>)];
// for one producer at a time
Node* last;
char pad3[CACHE_LINE_SIZE - sizeof(Node*)];
// shared among producers
atomic<bool> producerLock;
char pad4[CACHE_LINE_SIZE - sizeof(atomic<bool>)];
void Produce( const T& t ) {
Node* tmp = new Node( new T(t) );
while( producerLock.exchange(true) )
{ } // acquire exclusivity
last->next = tmp; // publish to consumers
last = tmp; // swing last forward
producerLock = false; // release exclusivity
}
First, we want to do as much work as possible outside the critical section of code that actually updates the queue(尽量在临界区之外“干活”). In this case, we can do all of the allocation and construction of the new node and its value concurrently with any number of other producers and consumers.Second, we “commit” the change by getting exclusive access to the tail of the queue.
bool Consume( T& result ) {
while( consumerLock.exchange(true) )
{ } // acquire exclusivity
Node* theFirst = first;
Node* theNext = first-> next;
if( theNext != nullptr ) { // if queue is nonempty
T* val = theNext->value; // take it out
theNext->value = nullptr; // of the Node
first = theNext; // swing first forward
consumerLock = false; // release exclusivity
result = *val; // now copy it back
delete val; // clean up the value
delete theFirst; // and the old dummy
return true; // and report success
}else{
consumerLock = false; // release exclusivity
return false; // report queue was empty
}
}
ring buffer
- 判断缓冲区是满还是空,在环形缓冲区(ring buffer)中是一个重点问题,在维基百科(http://en.wikipedia.org/wiki/Circular_buffer)中,讲解了五种判断方法,感兴趣可以看一下。在平衡各方优缺点后,本节重点讲解 镜像指示位方法,在linux和RT-Thread实现的环形缓冲区中,也都是用的该策略(或者说是该策略的扩展)。
- 镜像指示位:缓冲区的长度如果是n,逻辑地址空间则为0至n-1;那么,规定n至2n-1为镜像逻辑地址空间。本策略规定读写指针的地址空间为0至2n-1,其中低半部分对应于常规的逻辑地址空间,高半部分对应于镜像逻辑地址空间。当指针值大于等于2n时,使其折返(wrapped)到ptr-2n。使用一位表示写指针或读指针是否进入了虚拟的镜像存储区:置位表示进入,不置位表示没进入还在基本存储区。在读写指针的值相同情况下,如果二者的指示位相同,说明缓冲区为空;如果二者的指示位不同,说明缓冲区为满。这种方法优点是测试缓冲区满/空很简单;不需要做取余数操作;读写线程可以分别设计专用算法策略,能实现精致的并发控制。 缺点是读写指针各需要额外的一位作为指示位。如果缓冲区长度是2的幂,则本方法可以省略镜像指示位。如果读写指针的值相等,则缓冲区为空;如果读写指针相差n,则缓冲区为满,这可以用条件表达式(写指针 == (读指针 异或 缓冲区长度))来判断。PS: 本质是如果满了,则 读写指针 一定是一个在逻辑地址空间 一个在镜像逻辑地址空间。
- 在linux内核中,kfifo就是ring buffer的经典实现方式。
- 其会对所传入的size大小进行扩展,使其满足size为2的幂。这样如果缓冲区的长度是2的幂,则可以省略镜像指示位。如果读写指针的值相等,则缓冲区为空;如果读写指针相差n(缓冲区大小),则缓冲区为满。
- kfifo对读操作和写操作的实现非常简洁。在进行读操作和写操作时,其充分利用了无符号整型的性质。在__kfifo_put(写操作)和__kfifo_get(读操作)时,in(写指针)和out(读指针)都是正向增加的,当达到最大值时,产生溢出,使得从0开始,进行循环使用。
- 当只有一个读进程/线程和一个写进程/线程时,无需加锁,也能保证访问安全。在多进程/线程中,对同一个环形缓冲区进行读写操作时,需要加上锁,不然存在访问不安全问题;
小结
其实多线程竞争 从lock-based 演化为 lock-free ,消息通信。 io 通信从bio 也演化为 reactor 模式,也是事件通知 这里面有点意思
个人微信订阅号