简介
为什么要无锁编程?深入理解无锁编程
- 异步比同步要好
- 非阻塞比阻塞要好,而锁会引起阻塞,线程一直在跑就是正常的cpu调度,阻塞唤醒一次则意味着两次cpu调度,且竞争比较激烈的时候,一次唤醒所有等待锁的线程又会带来阻塞。PS: 加锁还会进入内核态,但单纯执行CAS指令却不会。
加锁会大大拖慢我们的性能。在获取锁过程中,CPU 没有去执行计算的相关指令,而要等待操作系统或者 JVM 来进行锁竞争的裁决。而那些没有拿到锁而被挂起等待的线程,则需要进行上下文切换。这个上下文切换,会把挂起线程的寄存器里的数据放到线程的程序栈里面去。这也意味着,加载到高速缓存里面的数据也失效了,程序就变得更慢了。
从某种意义上来讲,所谓的无锁,仅仅只是颗粒度特别小的“锁”罢了,从代码层面上逐渐降低级别到CPU的指令级别而已,总会在某个层级上付出等待的代价,除非逻辑上彼此完全无关。
硬件基础
“无锁“本质是什么。CPU对数据的读、写,是针对L1 Cache。数据如果不在L1中,先要从下层(L2、L3、Memory)读入L1,再在L1中读、写,可以认为CPU只能针对L1读写数据。L1 Cache有一个CacheLine的概念。一个CacheLine 64字节,除了数据外,还有一些标志位。(个别有128字节,或其他)读、写时,先把数据所在CacheLine,从下层读入L1,再在L1中读、写块中指定的字节。多数CPU,x64、大部分的ARM等,在不跨L1 CacheLine的情况下,一次读、写都是原子的。
- 读、写并发时,读与写是否需要用锁来保障一致性?一个指针8个字节,有没有可能我读前4个字节时,后4个字节被其他进/线程给改了,导致我读出的8个字节,一半是新数据、一半是老数据。根据前文,如果可以保证指针的8个字节不跨CacheLine,读“指针”就是原子操作,不会读到一半新、一半旧的数据。所以结论是,保证指针不跨CacheLine,不需要锁。
- 一个Core写L1 的CacheLine时,为了保证对应的内存不会出现写了前一半,后一半被另外Core写了,Core间也是需要同步的。但这个“同步”被优化了,MESI协议就是用来优化这个同步的,不会每次读、写都同步,只要必要的时候同步。可以把MESI保证的一致性,称为原子性。
- 写、写并发。两个进/线程在两个核上同时发起对指针的写操作,这个写操作是原子的,不会出现一个人写了前一半、另一个人写后一半。但是,当进/线程2修改指针时,它并不知道进/线程1刚刚完成了指针的修改。这就是“同步”问题,这里的关键就是,“后完成的覆盖了先完成的修改”。如何让“后完成的”在修改时,能感知到指针已经被修改了?CPU专门提供了一个指令,比如x64中有一个可以加LOCK前缀的“比较并交换”指令:
LOCK cmpxchg reg, (mem)
(也就是cas?CPU有仲裁机制)可以感知到其他Core最新的修改。- 脏读:当一个线程从主存拿了一个变量1修改后变成2存放在CPU缓存,还没来得及同步回主存时,另外一个线程又直接从主存读取变量为1,这样就出现了脏读。
- 这个过程非常耗时,CPU中普通的指令,通常只要1个周期。就算是乘、除这样复杂的指令,十几个周期也能完成大部分乘除指令。
LOCK cmpxchg reg, (mem)
指令至少一两百周期。在多路CPU的服务器中,甚至要400周期以上,是普通指令的几十、几百倍。因此无锁可并不意味着低延迟、高性能。 LOCK cmpxchg
一次修改的内存,最多只能是8个字节,64个二进制位。如果想并发的读、写超过64位,使用一条LOCK cmpxchg
指令,无法保证一致性。CPU一次读、写只能是64位(8字节),读、写超过8字节数据时,一定是多条指令,CPU不保证多条指令的原子性、一致性。这个时候,还是要使用“锁“。
PS:单条指令的执行不是原子的,分为取地址、读数据、计算、存数据等多个步骤,且还要考虑cache的问题,但对单个Core来说是原子的,os或硬件保证在Core执行完一个指令后再响应中断。但是对多个Core来说,单条指令的执行(针对同一个数据)是可能会彼此干扰的。 MESI 保证Core间读写并发受控 ==> LOCK cmpxchg
保证Core间写写并发受控 ==> (64bit OS)8字节的数据并发读写、写写安全 ==> 锁落实到底层是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 模式,也是事件通知 这里面有点意思
个人微信订阅号