技术

并发的成本 基础设施优化 hashicorp raft源码学习 docker 架构 mosn细节 与微服务框架整合 Java动态代理 编程范式 并发通信模型 《网络是怎样连接的》笔记 go细节 codereview mat使用 jvm 线程实现 go打包机制 go interface及反射 如何学习Kubernetes 《编译原理之美》笔记——后端部分 《编译原理之美》笔记——前端部分 Pilot MCP协议分析 go gc 内存管理玩法汇总 软件机制 istio流量管理 Pilot源码分析 golang io 学习Spring mosn源码浅析 MOSN简介 《datacenter as a computer》笔记 学习JVM Tomcat源码分析 Linux可观测性 MVCC 学习存储 学计算 Gotty源码分析 kubernetes operator kaggle泰坦尼克问题实践 kubernetes自动扩容缩容 神经网络模型优化 直觉上理解机器学习 knative入门 如何学习机器学习 神经网络系列笔记 TIDB源码分析 《阿里巴巴云原生实践15讲》笔记 Alibaba Java诊断工具Arthas TIDB存储——TIKV 《Apache Kafka源码分析》——简介 netty中的线程池 guava cache 源码分析 Springboot 启动过程分析 Spring 创建Bean的年代变迁 Linux内存管理 自定义CNI IPAM 扩展Kubernetes 副本一致性 spring redis 源码分析 kafka实践 spring kafka 源码分析 Linux进程调度 让kafka支持优先级队列 Codis源码分析 Redis源码分析 C语言学习 《趣谈Linux操作系统》笔记 docker和k8s安全机制 jvm crash分析 Prometheus 学习 Kubernetes监控 Kubernetes 控制器模型 容器日志采集 容器狂占cpu怎么办? 容器狂打日志怎么办? Kubernetes资源调度——scheduler 时序性数据库介绍及对比 influxdb入门 maven的基本概念 《Apache Kafka源码分析》——server Kubernetes objects之编排对象 源码分析体会 自动化mock AIOps说的啥 《数据结构与算法之美》——算法新解 Kubernetes源码分析——controller mananger Kubernetes源码分析——apiserver Kubernetes源码分析——kubelet Kubernetes介绍 ansible学习 Kubernetes源码分析——从kubectl开始 jib源码分析之Step实现 kubernetes实践 jib源码分析之细节 线程排队 跨主机容器通信 jib源码分析及应用 为容器选择一个合适的entrypoint kubernetes yaml配置 marathon-client 源码分析 《持续交付36讲》笔记 mybatis学习 程序猿应该知道的 无锁数据结构和算法 CNI 为什么很多业务程序猿觉得数据结构和算法没用? 串一串一致性协议 当我在说PaaS时,我在说什么 《数据结构与算法之美》——数据结构笔记 swagger PouchContainer技术分享体会 harbor学习 用groovy 来动态化你的代码 《深入剖析kubernetes》笔记 精简代码的利器——lombok 学习 编程语言的动态性 rxjava3——背压 rxjava2——线程切换 spring cloud 初识 《深入拆解java 虚拟机》笔记 《how tomcat works》笔记 hystrix 学习 rxjava1——概念 Redis 学习 TIDB 学习 分布式计算系统的那些套路 Storm 学习 AQS1——论文学习 Unsafe Spark Stream 学习 linux vfs轮廓 mysql 批量操作优化 《自己动手写docker》笔记 java8 实践 中本聪比特币白皮书 细读 区块链泛谈 比特币 大杂烩 总纲——如何学习分布式系统 hbase 泛谈 forkjoin 泛谈 看不见摸不着的cdn是啥 《jdk8 in action》笔记 程序猿视角看网络 bgp初识 mesos 的一些tips mesos 集成 calico calico学习 AQS2——粗略的代码分析 我们能用反射做什么 web 跨域问题 《clean code》笔记 硬件对软件设计的影响 《Elasticsearch权威指南》笔记 mockito简介及源码分析 2017软件开发小结—— 从做功能到做系统 《Apache Kafka源码分析》——clients dns隐藏的一个坑 《mysql技术内幕》笔记2 《mysql技术内幕》笔记1 log4j学习 为什么netty比较难懂? 回溯法 apollo client源码分析及看待面向对象设计 学习并发 从一个marathon的问题开始的 docker 环境(主要运行java项目)常见问题 Scala的一些梗 OpenTSDB 入门 spring事务小结 事务一致性 javascript应用在哪里 《netty in action》读书笔记 netty对http2协议的解析 ssl证书是什么东西 http那些事 苹果APNs推送框架pushy apple 推送那些事儿 编写java框架的几大利器 java内存模型 java exception Linux IO学习 network channel network byte buffer 测试环境docker化实践 netty(七)netty在框架中的使用套路 Nginx简单使用 《Linux内核设计的艺术》小结 Go并发机制及语言层工具 mesos深入 Macvlan Linux网络源代码学习——数据包的发送与接收 《docker源码分析》小结 docker中涉及到的一些linux知识 hystrix学习 Linux网络源代码学习——整体介绍 zookeeper三重奏 数据库的一些知识 Spark 泛谈 链式处理的那些套路 netty(六)netty回顾 Thrift基本原理与实践(二) Thrift基本原理与实践(一) 回调 异步执行抽象——Executor与Future Docker0.1.0源码分析 java gc Jedis源码分析 Redis概述 机器学习泛谈 Linux网络命令操作 JTA与TCC 换个角度看待设计模式 Scala初识 向Hadoop学习NIO的使用 以新的角度看数据结构 并发控制相关的硬件与内核支持 systemd 简介 那些有用的sql语句 异构数据库表在线同步 quartz 源码分析 基于docker搭建测试环境(二) spring aop 实现原理简述 自己动手写spring(八) 支持AOP 自己动手写spring(七) 类结构设计调整 分析log日志 自己动手写spring(六) 支持FactoryBean 自己动手写spring(九) 总结 自己动手写spring(五) bean的生命周期管理 自己动手写spring(四) 整合xml与注解方式 自己动手写spring(三) 支持注解方式 自己动手写spring(二) 创建一个bean工厂 自己动手写spring(一) 使用digester varnish 简单使用 关于docker image的那点事儿 基于docker搭建测试环境 分布式配置系统 JVM内存与执行 git spring rmi和thrift maven/ant/gradle使用 再看tcp mesos简介 缓存系统 java nio的多线程扩展 《Concurrency Models》笔记 回头看Spring IOC IntelliJ IDEA使用 Java泛型 vagrant 使用 Go常用的一些库 Python初学 Goroutine 调度模型 虚拟网络 《程序员的自我修养》小结 VPN(Virtual Private Network) Kubernetes存储 Kubernetes 其它特性 访问Kubernetes上的Service Kubernetes副本管理 Kubernetes pod 组件 使用etcd + confd + nginx做动态负载均衡 如何通过fleet unit files 来构建灵活的服务 CoreOS 安装 CoreOS 使用 Go学习 JVM类加载 硬币和扑克牌问题 LRU实现 virtualbox 使用 ThreadLocal小结 docker快速入门

标签


无锁数据结构和算法

2018年10月15日

简介

本文主要来自 drdobbs 系列博客,是作者08年写的,虽然一些观点有些过时,但很多表述非常有启发意义。

  1. 无锁编程的一些基本理念
  2. 常用数据结构的无锁化
  3. 是否所有数据结构都可以无锁化

为什么要无锁编程?

  1. 异步比同步要好
  2. 非阻塞比阻塞要好,而锁会引起阻塞,线程一直在跑就是正常的cpu调度,阻塞唤醒一次则意味着两次cpu调度,且竞争比较激烈的时候,一次唤醒所有等待锁的线程又会带来阻塞。

建议先看下 基于共享内存的数据通信问题

《软件架构设计》

实现无锁的几个粒度

  1. 只有一个线程写,一/多个线程读,仅靠内存屏障即可。PS:内存屏障保证了可见性,支持了有序性。
  2. 多个线程写,内存屏障 + CAS

基于内存屏障,有了Java中的volatile 关键字,再加上“单线程写” 原则,就有了Java中的Disruptor,其核心就是:一写多读,完全无锁。

Lock-Free Data Structures

Lock-Free Data Structures 要点如下

  1. In classic lock-based programming, whenever you need to share some data, you need to serialize access to it.
  2. 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?
  3. 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.
  4. 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.
  5. 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
  6. 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

  1. Reads have no locking at all.
  2. 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.
  3. 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

Lock-Free Programming

  1. 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?
  2. 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 需要硬件支持
  3. 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:

  1. 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. 下一小节有介绍
  2. 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). 如果你使用的编程语言不支持原子和有序性,你该如何模拟呢?

    1. 使用可对齐的变量类型,其自然支持原子操作
    2. 使操作有序,可以通过直接的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 模式,也是事件通知 这里面有点意思

个人微信订阅号