简介
为什么要无锁编程?深入理解无锁编程
- 异步比同步要好
- 非阻塞比阻塞要好,而锁会引起阻塞,线程一直在跑就是正常的cpu调度,阻塞唤醒一次则意味着两次cpu调度,且竞争比较激烈的时候,一次唤醒所有等待锁的线程又会带来阻塞。
加锁会大大拖慢我们的性能。在获取锁过程中,CPU 没有去执行计算的相关指令,而要等待操作系统或者 JVM 来进行锁竞争的裁决。而那些没有拿到锁而被挂起等待的线程,则需要进行上下文切换。这个上下文切换,会把挂起线程的寄存器里的数据放到线程的程序栈里面去。这也意味着,加载到高速缓存里面的数据也失效了,程序就变得更慢了。
程序里面的 CAS 调用,映射到我们的 CPU 硬件层面,就是一个机器指令,这个指令就是(Intel CPU) cmpxchg。
《软件架构设计》
实现无锁的几个粒度
- 只有一个线程写,一/多个线程读,仅靠内存屏障即可。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
}
}
小结
其实多线程竞争 从lock-based 演化为 lock-free ,消息通信。 io 通信从bio 也演化为 reactor 模式,也是事件通知 这里面有点意思
个人微信订阅号