技术

Python实践 下一个平台Agent 激发LLM涌现——提示工程 LLM微调理论及实践 大佬沉思 LLM外挂知识库 LLMOps 多模态LLM Python一些比较有意思的库 LLM部分技术源码学习 LangChain源码学习 通用分布式计算引擎Ray Python并发 go依赖注入 go collection gc的基本原理 golang性能分析及优化 数据湖 高性能计算与存储 Linux2.1.13网络源代码学习 《大数据经典论文解读》 三驾马车学习 Spark 内存管理及调优 Yarn学习 从Spark部署模式开始讲源码分析 容器狂占内存资源怎么办? 多角度理解一致性 golang io使用及优化模式 Flink学习 c++学习 学习ebpf go设计哲学 ceph学习 学习mesh kvm虚拟化 学习MQ go编译器以及defer实现 学习go 为什么要有堆栈 汇编语言 计算机组成原理 运行时和库 Prometheus client mysql 事务 mysql 事务的隔离级别 mysql 索引 坏味道 学习分布式 学习网络 学习Linux go堆内存分配 golang 系统调用与阻塞处理 Goroutine 调度过程 重新认识cpu mosn有的没的 负载均衡泛谈 单元测试的新解读 《Redis核心技术与实现》笔记 《Prometheus监控实战》笔记 Prometheus 告警学习 calico源码分析 对容器云平台的理解 Prometheus 源码分析 并发的成本 基础设施优化 hashicorp raft源码学习 docker 架构 mosn细节 与微服务框架整合 Java动态代理 编程范式 并发通信模型 《网络是怎样连接的》笔记 go channel codereview gc分析 jvm 线程实现 go打包机制 go interface及反射 如何学习Kubernetes 《编译原理之美》笔记——后端部分 《编译原理之美》笔记——前端部分 Pilot MCP协议分析 go gc 内存管理玩法汇总 软件机制 istio流量管理 Pilot源码分析 golang io 学习Spring mosn源码浅析 MOSN简介 《datacenter as a computer》笔记 学习JVM Tomcat源码分析 Linux可观测性 学习存储 学计算 Gotty源码分析 kubernetes operator kaggle泰坦尼克问题实践 kubernetes扩缩容 神经网络模型优化 直觉上理解深度学习 如何学习机器学习 TIDB源码分析 什么是云原生 Alibaba Java诊断工具Arthas TIDB存储——TIKV 《Apache Kafka源码分析》——简介 netty中的线程池 guava cache 源码分析 Springboot 启动过程分析 Spring 创建Bean的年代变迁 Linux内存管理 自定义CNI IPAM 共识算法 spring redis 源码分析 kafka实践 spring kafka 源码分析 Linux进程调度 让kafka支持优先级队列 Codis源码分析 Redis源码分析 C语言学习 《趣谈Linux操作系统》笔记 docker和k8s安全访问机制 jvm crash分析 Prometheus 学习 Kubernetes监控 容器日志采集 Kubernetes 控制器模型 容器狂占资源怎么办? Kubernetes资源调度——scheduler 时序性数据库介绍及对比 influxdb入门 maven的基本概念 《Apache Kafka源码分析》——server Kubernetes类型系统 源码分析体会 《数据结构与算法之美》——算法新解 Kubernetes源码分析——controller mananger Kubernetes源码分析——apiserver Kubernetes源码分析——kubelet Kubernetes介绍 ansible学习 Kubernetes源码分析——从kubectl开始 jib源码分析之Step实现 jib源码分析之细节 线程排队 跨主机容器通信 jib源码分析及应用 为容器选择一个合适的entrypoint kubernetes yaml配置 《持续交付36讲》笔记 mybatis学习 程序猿应该知道的 无锁数据结构和算法 CNI——容器网络是如何打通的 为什么很多业务程序猿觉得数据结构和算法没用? 串一串一致性协议 当我在说PaaS时,我在说什么 《数据结构与算法之美》——数据结构笔记 PouchContainer技术分享体会 harbor学习 用groovy 来动态化你的代码 精简代码的利器——lombok 学习 《深入剖析kubernetes》笔记 编程语言那些事儿 rxjava3——背压 rxjava2——线程切换 spring cloud 初识 《深入拆解java 虚拟机》笔记 《how tomcat works》笔记 hystrix 学习 rxjava1——概念 Redis 学习 TIDB 学习 如何分发计算 Storm 学习 AQS1——论文学习 Unsafe Spark Stream 学习 linux vfs轮廓 《自己动手写docker》笔记 java8 实践 中本聪比特币白皮书 细读 区块链泛谈 比特币 大杂烩 总纲——如何学习分布式系统 hbase 泛谈 forkjoin 泛谈 看不见摸不着的cdn是啥 《jdk8 in action》笔记 程序猿视角看网络 bgp初识 calico学习 AQS——粗略的代码分析 我们能用反射做什么 web 跨域问题 《clean code》笔记 《Elasticsearch权威指南》笔记 mockito简介及源码分析 2017软件开发小结—— 从做功能到做系统 《Apache Kafka源码分析》——clients dns隐藏的一个坑 《mysql技术内幕》笔记 log4j学习 为什么netty比较难懂? 递归、回溯、动态规划 apollo client源码分析及看待面向对象设计 学习并发 docker运行java项目的常见问题 OpenTSDB 入门 spring事务小结 分布式事务 javascript应用在哪里 《netty in action》读书笔记 netty对http2协议的解析 ssl证书是什么东西 http那些事 苹果APNs推送框架pushy apple 推送那些事儿 编写java框架的几大利器 java内存模型和jvm内存布局 java exception Linux IO学习 netty内存管理 测试环境docker化实践 netty在框架中的使用套路 Nginx简单使用 《Linux内核设计的艺术》小结 Go并发机制及语言层工具 Linux网络源代码学习——数据包的发送与接收 《docker源码分析》小结 docker namespace和cgroup zookeeper三重奏 数据库的一些知识 Spark 泛谈 链式处理的那些套路 netty回顾 Thrift基本原理与实践(二) Thrift基本原理与实践(一) 回调 异步执行抽象——Executor与Future Docker0.1.0源码分析 java gc Jedis源码分析 深度学习泛谈 Linux网络命令操作 JTA与TCC 换个角度看待设计模式 Scala初识 向Hadoop学习NIO的使用 以新的角度看数据结构 并发控制相关的硬件与内核支持 systemd 简介 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 maven/ant/gradle/make使用 再看tcp kv系统 java nio的多线程扩展 《Concurrency Models》笔记 回头看Spring IOC IntelliJ IDEA使用 Java泛型 vagrant 使用 Go常用的一些库 Python初学 Goroutine 调度模型 虚拟网络 《程序员的自我修养》小结 Kubernetes存储 访问Kubernetes上的Service Kubernetes副本管理 Kubernetes pod 组件 Go基础 JVM类加载 硬币和扑克牌问题 LRU实现 virtualbox 使用 ThreadLocal小结 docker快速入门

架构

大模型推理服务框架 模型服务化(未完成) 大模型RHLF 大模型训练 大模型推理 从Attention到Transformer k8s设备管理 LLM工具栈 ddd从理念到代码 如何应用LLM 小鼠如何驾驭大象(LLM)? 多类型负载协调员Koordinator controller-runtime细节分析 finops学习 kubevela多集群 kubevela中cue的应用 基于k8s的工作流 容器和CPU那些事儿 kubevela源码分析 数据集管理fluid 应用管理平台kubevela karmada支持crd 多集群管理 AutoML和AutoDL 特征平台 实时训练 分布式链路追踪 helm tensorflow原理——python层分析 如何学习tensorflow 数据并行——allreduce 数据并行——ps 机器学习中的python调用c 机器学习训练框架概述 embedding的原理及实践 tensornet源码分析 大模型训练和推理 X的生成——特征工程 tvm tensorflow原理——core层分析 模型演变 《深度学习推荐系统实战》笔记 keras 和 Estimator tensorflow分布式训练 分布式训练的一些问题 基于Volcano的弹性训练 图神经网络 pytorch弹性分布式训练 从混部到统一调度 从RNN到Attention pytorch分布式训练 CNN 《动手学深度学习》笔记 pytorch与线性回归 多活 volcano特性源码分析 推理服务 kubebuilder 学习 mpi 学习pytorch client-go学习 tensorflow学习 提高gpu 利用率 GPU与容器的结合 GPU入门 AI云平台梳理 tf-operator源码分析 k8s批处理调度/Job调度 喜马拉雅容器化实践 Kubernetes 实践 学习rpc BFF openkruise学习 可观察性和监控系统 基于Kubernetes选主及应用 《许式伟的架构课》笔记 Admission Controller 与 Admission Webhook 发布平台系统设计 k8s水平扩缩容 Scheduler如何给Node打分 Scheduler扩展 深入controller openkruise cloneset学习 controller-runtime源码分析 pv与pvc实现 csi学习 client-go informer源码分析 kubelet 组件分析 调度实践 Pod是如何被创建出来的? 《软件设计之美》笔记 mecha 架构学习 Kubernetes events学习及应用 CRI 资源调度泛谈 业务系统设计原则 grpc学习 元编程 以应用为中心 istio学习 下一代微服务Service Mesh 《实现领域驱动设计》笔记 概率论 serverless 泛谈 《架构整洁之道》笔记 处理复杂性 那些年追过的并发 服务器端编程 网络通信协议 架构大杂烩 如何学习架构 《反应式设计模式》笔记 项目的演化特点 反应式架构摸索 函数式编程的设计模式 服务化 ddd反模式——CRUD的败笔 研发效能平台 重新看面向对象设计 业务系统设计的一些体会 函数式编程 《左耳听风》笔记 业务程序猿眼中的微服务管理 DDD实践——CQRS 项目隔离——案例研究 《编程的本质》笔记 系统故障排查汇总及教训 平台支持类系统的几个点 代码腾挪的艺术 abtest 系统设计汇总 《从0开始学架构》笔记 初级权限系统设计 领域驱动理念 现有上传协议分析 移动网络下的文件上传要注意的几个问题 推送系统的几个基本问题 做配置中心要想好的几个基本问题 不同层面的异步 分层那些事儿 性能问题分析 用户认证问题 资源的分配与回收——池 消息/任务队列

标签

k8s设备管理 多类型负载协调员Koordinator controller-runtime细节分析 finops学习 kubevela多集群 kubevela中cue的应用 基于k8s的工作流 容器和CPU那些事儿 kubevela源码分析 数据集管理fluid 应用管理平台kubevela karmada支持crd 多集群管理 helm 从混部到统一调度 volcano特性源码分析 kubebuilder 学习 client-go学习 tf-operator源码分析 k8s批处理调度/Job调度 喜马拉雅容器化实践 Kubernetes 实践 openkruise学习 基于Kubernetes选主及应用 Admission Controller 与 Admission Webhook k8s水平扩缩容 Scheduler如何给Node打分 Scheduler扩展 深入controller openkruise cloneset学习 controller-runtime源码分析 pv与pvc实现 csi学习 client-go informer源码分析 kubelet 组件分析 调度实践 Pod是如何被创建出来的? Kubernetes events学习及应用 CRI 资源调度泛谈 如何学习Kubernetes 以应用为中心 kubernetes operator kubernetes扩缩容 serverless 泛谈 什么是云原生 自定义CNI IPAM docker和k8s安全访问机制 Kubernetes监控 Kubernetes 控制器模型 Kubernetes资源调度——scheduler Kubernetes类型系统 Kubernetes源码分析——controller mananger Kubernetes源码分析——apiserver Kubernetes源码分析——kubelet Kubernetes介绍 Kubernetes源码分析——从kubectl开始 kubernetes yaml配置 CNI——容器网络是如何打通的 当我在说PaaS时,我在说什么 《深入剖析kubernetes》笔记 Kubernetes存储 访问Kubernetes上的Service Kubernetes副本管理 Kubernetes pod 组件

无锁数据结构和算法

2018年10月15日

简介

为什么要无锁编程?深入理解无锁编程

  1. 异步比同步要好
  2. 非阻塞比阻塞要好,而锁会引起阻塞,线程一直在跑就是正常的cpu调度,阻塞唤醒一次则意味着两次cpu调度,且竞争比较激烈的时候,一次唤醒所有等待锁的线程又会带来阻塞。PS: 加锁还会进入内核态,但单纯执行CAS指令却不会。

加锁会大大拖慢我们的性能。在获取锁过程中,CPU 没有去执行计算的相关指令,而要等待操作系统或者 JVM 来进行锁竞争的裁决。而那些没有拿到锁而被挂起等待的线程,则需要进行上下文切换。这个上下文切换,会把挂起线程的寄存器里的数据放到线程的程序栈里面去。这也意味着,加载到高速缓存里面的数据也失效了,程序就变得更慢了。

从某种意义上来讲,所谓的无锁,仅仅只是颗粒度特别小的“锁”罢了,从代码层面上逐渐降低级别到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
	}
}

ring buffer

ring buffer,一篇文章讲透它?

  1. 判断缓冲区是满还是空,在环形缓冲区(ring buffer)中是一个重点问题,在维基百科(http://en.wikipedia.org/wiki/Circular_buffer)中,讲解了五种判断方法,感兴趣可以看一下。在平衡各方优缺点后,本节重点讲解 镜像指示位方法,在linux和RT-Thread实现的环形缓冲区中,也都是用的该策略(或者说是该策略的扩展)。
  2. 镜像指示位:缓冲区的长度如果是n,逻辑地址空间则为0至n-1;那么,规定n至2n-1为镜像逻辑地址空间。本策略规定读写指针的地址空间为0至2n-1,其中低半部分对应于常规的逻辑地址空间,高半部分对应于镜像逻辑地址空间。当指针值大于等于2n时,使其折返(wrapped)到ptr-2n。使用一位表示写指针或读指针是否进入了虚拟的镜像存储区:置位表示进入,不置位表示没进入还在基本存储区。在读写指针的值相同情况下,如果二者的指示位相同,说明缓冲区为空;如果二者的指示位不同,说明缓冲区为满。这种方法优点是测试缓冲区满/空很简单;不需要做取余数操作;读写线程可以分别设计专用算法策略,能实现精致的并发控制。 缺点是读写指针各需要额外的一位作为指示位。如果缓冲区长度是2的幂,则本方法可以省略镜像指示位。如果读写指针的值相等,则缓冲区为空;如果读写指针相差n,则缓冲区为满,这可以用条件表达式(写指针 == (读指针 异或 缓冲区长度))来判断。PS: 本质是如果满了,则 读写指针 一定是一个在逻辑地址空间 一个在镜像逻辑地址空间
  3. 在linux内核中,kfifo就是ring buffer的经典实现方式。
    1. 其会对所传入的size大小进行扩展,使其满足size为2的幂。这样如果缓冲区的长度是2的幂,则可以省略镜像指示位。如果读写指针的值相等,则缓冲区为空;如果读写指针相差n(缓冲区大小),则缓冲区为满。
    2. kfifo对读操作和写操作的实现非常简洁。在进行读操作和写操作时,其充分利用了无符号整型的性质。在__kfifo_put(写操作)和__kfifo_get(读操作)时,in(写指针)和out(读指针)都是正向增加的,当达到最大值时,产生溢出,使得从0开始,进行循环使用。
    3. 当只有一个读进程/线程和一个写进程/线程时,无需加锁,也能保证访问安全。在多进程/线程中,对同一个环形缓冲区进行读写操作时,需要加上锁,不然存在访问不安全问题;

小结

其实多线程竞争 从lock-based 演化为 lock-free ,消息通信。 io 通信从bio 也演化为 reactor 模式,也是事件通知 这里面有点意思

个人微信订阅号