在上一篇中说到了mailbox_t的底层实际上使用了管道ypipe_t来存储命令。而ypipe_t实质上是一个无锁队列,其底层使用了yqueue_t队列,ypipe_t是对yueue_t的再包装,所以我们先来看看yqueue_t是怎么实现的。

1、yqueue_t

yqueue_t是一个高效的队列,高效体现在她的内存配置上,尽量少的申请内存,尽量重用将要释放的内存。其实,容器的设计都会涉及这点--高效的内存配置器,像sgi stl容器的内存配置器,使用了内存池,预先分配一块较大内存,用不同大小的桶管理,容器申请内存时从相应的桶里拿一块内存,释放内存时又把内存回收到相应的桶里,这样就能做到尽量少的malloc调用。yqueue_t并没有使用内存池,但是利用了同样的思想,一次性分配一个chunk_t减少内存分配次数,并用spare_chunk管理将要释放的块用于内存回收,详细的实现后面再说,先看一下yqueue_t的整个概况,源码位于Yqueue.hpp

  1. // T is the type of the object in the queue.队列中元素的类型
  2. // N is granularity(粒度) of the queue,简单来说就是yqueue_t一个结点可以装载N个T类型的元素,可以猜想yqueue_t的一个结点应该是个数组
  3. template <typename T, int N> class yqueue_t
  4. {
  5. public:
  6. inline yqueue_t ();// Create the queue.
  7. inline ~yqueue_t ();// Destroy the queue.
  8. inline T &front ();// Returns reference to the front element of the queue. If the queue is empty, behaviour is undefined.
  9. inline T &back ();// Returns reference to the back element of the queue.If the queue is empty, behaviour is undefined.
  10. inline void push ();// Adds an element to the back end of the queue.
  11. inline void pop ();// Removes an element from the front of the queue.
  12.   inline void unpush ()// 用于回滚操作,暂时先不管这个函数,用到再说
  13. private:
  14. // Individual memory chunk to hold N elements.
  15. struct chunk_t
  16. {
  17. T values [N];
  18. chunk_t *prev;
  19. chunk_t *next;
  20. };
  21.  
  22. chunk_t *begin_chunk;
  23. int begin_pos;
  24. chunk_t *back_chunk;
  25. int back_pos;
  26. chunk_t *end_chunk;
  27. int end_pos;
  28.  
  29. atomic_ptr_t<chunk_t> spare_chunk; //空闲块(我把所有元素都已经出队的块称为空闲块),读写线程的共享变量
  30. };

可以看到,yqueue_t是采用双向链表实现的,链表结点称之为chunk_t,每个chunk_t可以容纳N个T类型的元素,以后就以一个chunk_t为单位申请内存,begin_chunk可以理解为链表头结点,back_chunk可以理解为队列中最后一个元素所在的链表结点,我们知道容器都应该要能动态扩容的,end_chunk就是拿来扩容的,总是指向链表的最后一个结点,而spare_chunk表示最近的被踢出队列的链表结点。入队操作back_chunk和back_pos,back_chunk结点填满元素时该扩容,让end_chunk指向新的链表结点或者之前释放的链表结点,出队操作begin_chunk和begin_pos,begin_chunk所有元素都出完后并不释放内存,而是让spare_chunk指向他,然后释放spare_chunk上一次的指针,这样扩容的时候就可以重新使用这个结点了。begin_chunk,begin_pos,back_chunk,back_pos,end_chunk,end_pos的关系大致如下:

这里需要重点说一下spare_chunk,根据上面的描述,扩容(写线程的事)和出队列(写线程的事)都会用到这个变量,所以这个变量是读写共享的,有同步的语义,zmq用了atomic_ptr_t<T>来做同步,atomic_ptr_t同样可以看成是一个指针,结构上atomic_ptr_t内含一个指针,提供了两个原子操作和一个非原子操作,在yqueue_t中就需要用到其中一个原子操作xchg。

  1. // This class encapsulates several atomic operations on pointers.
  2. template <typename T> class atomic_ptr_t
  3. {
  4. public:
  5. inline void set (T *ptr_);//非原子操作
  6. inline T *xchg (T *val_);//原子操作
  7. inline T *cas (T *cmp_, T *val_);//原子操作
  8. private:
  9. volatile T *ptr;
  10. }
  • set函数,把私有成员ptr指针设置成参数ptr_的值,不是一个原子操作,需要使用者确保执行set过程没有其他线程使用ptr的值
  • xchg函数,把私有成员ptr指针设置成参数val_的值,并返回ptr设置之前的值。原子操作,操作系统保证线程安全
  • cas函数,把私有成员ptr指针与参数cmp_指针比较,如果相等,就把ptr设置为参数val_的值,返回ptr设置之前的值;如果直接返回ptr值。原子操作,操作系统保证线程安全

在实现上xchg和cas函数就是包装了各种cpu提供的xchg和cas原子操作,想了解原理的可以查一查着方面的资料,这里只需要知道有这个功能就可以了。

有了这个指针,就可以保证单个读线程和单个写线程时的线程安全了。

接着,来看下yqueue_t是如何构造、push、pop的。后面我会把begin_chunk和begin_pos合起来成为队头指针,back_chunk和back_pos合起来成为队尾指针,end_chunk和end_pos合起来称为容器指针

①构造yqueue_t

  1. inline yqueue_t ()
  2. {
  3. begin_chunk = (chunk_t*) malloc (sizeof (chunk_t));
  4. alloc_assert (begin_chunk);
  5. begin_pos = ;
  6. back_chunk = NULL;//back_chunk总是指向队列中最后一个元素所在的链表结点,现在还没有元素,所以初始为空
  7. back_pos = ;
  8. end_chunk = begin_chunk;//end_chunk总是指向链表的最后一个结点
  9. end_pos = ;
  10. }

pop

  1. // Removes an element from the front end of the queue.
  2. inline void pop ()
  3. {
  4. if (++ begin_pos == N) {
  5. chunk_t *o = begin_chunk;
  6. begin_chunk = begin_chunk->next;
  7. begin_chunk->prev = NULL;
  8. begin_pos = ;
  9.  
  10. // 'o' has been more recently used than spare_chunk,
  11. // so for cache reasons we'll get rid of the spare and
  12. // use 'o' as the spare.
  13. chunk_t *cs = spare_chunk.xchg (o);//由于局部性原理,总是保存最新的空闲块而释放先前的空闲快
  14. free (cs);
  15. }
  16. }

主要是链表的基本操作。pop虽然只有几行代码,却也有两个点需要注意:

  1. pop掉的元素,其销毁工作交给调用者完成
  2. 空闲块的保存,要求是原子操作。这得想明白为什么。原因是,空闲块是读写线程的共享变量,需要做同步,我们会在push中看到,push使用了spare_chunk。

push

  1. inline void push ()
  2. {
  3. back_chunk = end_chunk;
  4. back_pos = end_pos;
  5.  
  6. if (++end_pos != N)//end_pos==N表明这个链表结点已经满了
  7. return;
  8.  
  9. chunk_t *sc = spare_chunk.xchg (NULL);
  10. if (sc) {
  11. end_chunk->next = sc;
  12. sc->prev = end_chunk;
  13. } else {
  14. end_chunk->next = (chunk_t*) malloc (sizeof (chunk_t));
  15. alloc_assert (end_chunk->next);
  16. end_chunk->next->prev = end_chunk;
  17. }
  18. end_chunk = end_chunk->next;
  19. end_pos = 0;
  20. }

push操作并未真正的push一个元素,只是把队尾指针指向容器指针,然后让容器指针加1,所以,这二者的值总是差1,二者的关系在第2节中的四个图中可以看的更清楚。扩容的条件是容器指针到达了容器尾(所以end_chunk是拿来扩容的),扩容时先去spare_chunk拿之前废弃的块(所有元素都被pop的块),拿到了就重用,没拿到就得重新申请。同样需要注意,拿空闲块需要做同步操作。

当end_pos==N时,需要扩容,如下:

④front、back

这两个函数需要注意的点是,返回的是引用,是个左值,调用者可以通过二者修改容器的值。

  1. // Returns reference to the front element of the queue.
  2. // If the queue is empty, behaviour is undefined.
  3. inline T &front ()
  4. {
  5. return begin_chunk->values [begin_pos];
  6. }
  7.  
  8. // Returns reference to the back element of the queue.
  9. // If the queue is empty, behaviour is undefined.
  10. inline T &back ()
  11. {
  12. return back_chunk->values [back_pos];
  13. }

总的来说yqueue_t还是比较好理解,现在可以来看一看ypipe_t的实现。

2、ypipe_t

先看下ypipe_t的介绍(注释)、类继承关系、类接口及数据成员

  1. // Lock-free queue implementation.
  2. // Only a single thread can read from the pipe at any specific moment.
  3. // Only a single thread can write to the pipe at any specific moment.
  4. // T is the type of the object in the queue.
  5. // N is granularity of the pipe, i.e. how many items are needed to
  6. // perform next memory allocation.
  7. template <typename T, int N> class ypipe_t : public ypipe_base_t<T,N>
  8.  
  9. template <typename T, int N> class ypipe_base_t
  10. {
  11. public:
  12. virtual ~ypipe_base_t () {}
  13. virtual void write (const T &value_, bool incomplete_) = ;
  14. virtual bool unwrite (T *value_) = ;
  15. virtual bool flush () = ;
  16. virtual bool check_read () = ;
  17. virtual bool read (T *value_) = ;
  18. virtual bool probe (bool (*fn)(T &)) = ;
  19. };
  20. template <typename T, int N> class ypipe_t : public ypipe_base_t<T,N>
  21. {
  22. protected:
  23. // Allocation-efficient queue to store pipe items.
  24. // Front of the queue points to the first prefetched item, back of the pipe points to last un-flushed item.
  25. // Front is used only by reader thread, while back is used only by writer thread.
  26. yqueue_t <T, N> queue;//底层容器
  27.  
  28. // Points to the first un-flushed item. This variable is used exclusively by writer thread.
  29. T *w;//指向第一个未刷新的元素,只被写线程使用
  30. // Points to the first un-prefetched item. This variable is used exclusively by reader thread.
  31. T *r;//指向第一个还没预提取的元素,只被读线程使用
  32. // Points to the first item to be flushed in the future.
  33. T *f;//指向下一轮要被刷新的一批元素中的第一个
  34. // The single point of contention between writer and reader thread.
  35. // Points past the last flushed item. If it is NULL,reader is asleep.
  36. // This pointer should be always accessed using atomic operations.
  37. atomic_ptr_t <T> c;//读写线程共享的指针,指向每一轮刷新的起点(看代码的时候会详细说)。当c为空时,表示读线程睡眠(只会在读线程中被设置为空)
  38. }

ypipe_t继承自ypipe_base_t,其提供了一组操作管道的接口,从ypipe_t源码来看,他只是实现了这组接口,并没有提供其他的方法了。T、N在yqueue_t中已经详细说过了。从数据成员来看,其底层使用了上面讲到的yqueue_t,可以猜想,ypipe_t的write、read等操作往yqueue_t中写数据读数据。ypipe_t开头的的注释中写道,ypipe_t是一个无锁队列的实现,单个读单个写同时操作ypipe_t是线程安全的。有没有发现这就是一个生产者消费者的问题,写线程是生产者,读线程是消费者,yqueue_t就是缓冲区,由于只有一个生产者、一个消费者,并不涉及同类线程间的互斥,只需读线程和写线程同步就可以了,操作系统课程中的解法就是两个信号量+PV操作,涉及到锁,而这里是无锁,其实就是使用了数据成员中的三个指针w、r、c来实现的。至于f指针,是用来保证数据完整性的,zmq中一个完整的数据是可以分成多段往ypipe_t中写的(下面源码的write函数incomplete_参数),只有数据写完整了才允许读线程去读数据,关于这点,可以在session与socket_base_t实例的通信中看到,后面会有文章专门详细介绍,我们前面说过的mailbox_t底层也使用了ypipe_t,但mailbox不会把命令分段,每次都是完整的数据。那么接下来就看看这几个指针时如何协同工作的吧。

先看ypipe_t构造的时候做了什么事情:

  1. // Initialises the pipe.
  2. inline ypipe_t ()
  3. {
  4. // Insert terminator element into the queue.
  5. queue.push ();//yqueue_t的尾指针加1,开始back_chunk为空,现在back_chunk指向第一个chunk_t块的第一个位置
  6. // Let all the pointers to point to the terminator.
  7. r = w = f = &queue.back ();
  8. c.set (&queue.back ());
  9. }

在ypipe_t中,back_chunk+back_pos类似vector的end迭代器,上面的注释"Let all the pointers to point to the terminator."也是这个意思,就是让r、w、f、c四个指针都指向这个end迭代器,有关这点在write的时候能看清晰的感受到。那么做完这一步,他们关系像下面这个样子:

ps.后面7个格子都属于同一个chunk_t块(yqueue_t介绍了chunk_t结点内含一个数组)

现在看看如何往queue写数据:

  1. inline void write (const T &value_, bool incomplete_)
  2. {
  3. // Place the value to the queue, add new terminator element.
  4. queue.back () = value_;
  5. queue.push ();
  6.  
  7. // Move the "flush up to here" poiter.
  8. if (!incomplete_)
  9. f = &queue.back ();
  10. }

write往ypipe_t的end迭代器写入内容,然后让end迭代器下移一个位置,参数incomplete_=true表示数据分段,现在写的只是其中一段,当incomplete=false时所有数据段都写完了,把指针f指向end迭代器,所以从w指针到f指针这一段表示一个完整的数据。假设完整的数据为ABC,现在把数据分三段A、B、C写入ypipe_t,调用write的形式为:

  1. write(A,true);
  2. some code;
  3. write(B,true);
  4. some code;
  5. write(C,false);
  6. some code;

这时w,f,r,c的关系如下图:

当一个完整的数据写完后,写线程会调用flush函数,让读线程看到这个完整的数据,如果读线程睡眠了,写线程有义务唤醒读线程。这里涉及了几个点:

  1. 如何让读线程看到这个数据?
  2. 如何判断读线程睡眠?
  3. 读线程睡眠时,写线程如何通知读线程?
  4. 如何刷新

然后带着这四个问题来看看flush函数的实现:

  1. inline bool flush ()
  2. {
  3. // If there are no un-flushed items, do nothing.
  4. if (w == f)
  5. return true;
  6.  
  7. // Try to set 'c' to 'f'.
  8. if (c.cas (w, f) != w) {
  9. // Compare-and-swap was unseccessful because 'c' is NULL.
  10. // This means that the reader is asleep. Therefore we don't care about thread-safeness and update c in non-atomic manner.
  11. // We'll return false to let the caller know that reader is sleeping.
  12. c.set (f);
  13. w = f;
  14. return false;
  15. }
  16.  
  17. // Reader is alive. Nothing special to do now. Just move the 'first un-flushed item' pointer to 'f'.
  18. w = f;
  19. return true;
  20. }

可以看到w==f 时,flush是直接返回的,什么也没做,而当write函数的incomplete_=false时,把 f 指向了新的结点,这个时候 w!=f 了,flush函数才有所作为,所以w、f指针合作可用来告知flush函数现在能否刷新。

当w!=f时,真正执行刷新,可以看到所谓的刷新只做了两件事情,c=f和w=f,其中c是读写线程共享的指针,所以用了原子操作cas来完成c=f的功能。cas这个函数我们在queue_t中也说过了,这里有必要再说一下她的大概实现:

  1. T* cas(w,f){
  2. ret=c ;
  3. if(c==w)
  4. c = f;
  5. return ret;
  6. }

可以看到c!=w时,设置失败,并返回当前c的值。在写线程中c和w总是指向同一个值的,都是指向f(刷新的目的就是两个赋值,c=f和w=f),只有被读线程改写的情况下c!=w才成立,而读线程只在一种情况下改写c,那就是队列中没有数据时,读线程把c置NULL然后睡眠,这点在说read的源码时会看到。所以,cas的返回值代表了读线程的状态,返回NULL,说明读线程睡眠了,此时cas没有成功,所以需要使用set函数,把c指向f。这样就完成了刷新工作。

先来回答上面的4个问题

  1. 如何让读线程看到这个数据?
    令c=f,读线程会检查指针c,判断是否有数据
  2. 如何判断读线程睡眠?
    c.cas(w,f)返回NULL,读线程睡眠
  3. 读线程睡眠时,写线程如何通知读线程?
    flush函数返回false,表明读线程睡眠了,写线程看到flush返回false之后会发送一个消息给读线程。关于这点可以看上一篇中mailbox的send函数源码
  4. 如何刷新
    c=f ; w=f

再看一下刷新之后,w、f、c、r的关系:

再来看一下读线程如何read:

  1. // Reads an item from the pipe. Returns false if there is no value available.
  2. inline bool read (T *value_)
  3. {
  4. // Try to prefetch a value.
  5. if (!check_read ())
  6. return false;
  7.  
  8. // There was at least one value prefetched.Return it to the caller.
  9. *value_ = queue.front ();
  10. queue.pop ();
  11. return true;
  12. }

可以看到,read函数会先检查队列中是否有数据可读,如果没有数据可读直接就返回了,如果有数据可读,会在check_read中预取数据。这里面有两个点,一个是检查是否有数据可读,一个是预取,所以带着这两个问题来看看check_read函数的源码:

  1. // Check whether item is available for reading.
  2. inline bool check_read ()
  3. {
  4. // Was the value prefetched already? If so, return.
  5. if (&queue.front () != r && r)//判断是否在前几次调用read函数时已经预取数据了return true;
  6.  
  7. // There's no prefetched value, so let us prefetch more values.
  8. // Prefetching is to simply retrieve the pointer from c in atomic fashion.
  9. // If there are no items to prefetch, set c to NULL (using compare-and-swap).
  10. r = c.cas (&queue.front (), NULL);//尝试预取数据
  11. // If there are no elements prefetched, exit.
  12. // During pipe's lifetime r should never be NULL, however,it can happen during pipe shutdown when items are being deallocated.
  13. if (&queue.front () == r || !r)//判断是否成功预取数据
  14. return false;
  15.  
  16. // There was at least one value prefetched.
  17. return true;
  18. }

可以看到,check_read是通过指针r的位置来判断是否有数据可读的:如果指针r指向的是队头元素(r==&queue.front())或者r没有指向任何元素(NULL)则说明队列中并没有可读的数据,这个时候check_read尝试去预取数据。所谓的预取就是令 r=c (cas函数就是返回c本身的值,看上面关于cas的实现), 而c在write中被指向f(见上图),这时从queue.front()到f这个位置的数据都被预取出来了,然后每次调用read都能取出一段。值得注意的是,当c==&queue.front()时,代表数据被取完了,这时把c指向NULL,接着读线程会睡眠,这也是给写线程检查读线程是否睡眠的标志。

继续上面写入ABC数据的场景,第一次调用read时,会先check_read,把指针r指向指针c的位置(所谓的预取),这时r,c,w,f的关系如下:

这时,&queue.front()!=r,读线程的就可以一直读数据了,直到队头到达了指针r的位置,表示没数据了,然后陷入睡眠。

综上,就是ypipe_t无锁队列的实现,再总结一下过程:

数据可分段,写线程一次写入一段,所有数据都写完后把f指向队列的end迭代器位置,用以表示下一轮的写位置,然后flush,把c和w指向end的位置,通知读线程,读线程check_read预取数据,把r也指向end位置,每次read的时候队头指针都下移一个位置,直到队头移动到r的位置,也就是end,表示没数据了,读线程把c指针置空,表示数据我都读完了,我要睡了,下次再喊我。

下一篇将介绍session与socket_base_t的消息通信,还要一段时间再更新。

zeromq源码分析笔记之无锁队列ypipe_t(3)的更多相关文章

  1. zeromq源码分析笔记之线程间收发命令(2)

    在zeromq源码分析笔记之架构说到了zmq的整体架构,可以看到线程间通信包括两类,一类是用于收发命令,告知对象该调用什么方法去做什么事情,命令的结构由command_t结构体确定:另一类是socke ...

  2. zeromq源码分析笔记之准备(0)

    zeromq这个库主要用于进程通信,包括本地进程.网络通信,涉及到一些基础知识,主要包括管道通信,socket编程的内容,反应器模式(使用IO多路复用实现),无锁队列这几块比较重要的部分,下面的几个链 ...

  3. zeromq源码分析笔记之架构(1)

    1.zmq概述 ZeroMQ是一种基于消息队列的多线程网络库,其对套接字类型.连接处理.帧.甚至路由的底层细节进行抽象,提供跨越多种传输协议的套接字.引用云风的话来说:ZeroMQ 并不是一个对 so ...

  4. ReentrantReadWriteLock源码分析笔记

    ReentrantReadWriteLock包含两把锁,一是读锁ReadLock, 此乃共享锁, 一是写锁WriteLock, 此乃排它锁. 这两把锁都是基于AQS来实现的. 下面通过源码来看看Ree ...

  5. ArrayList源码分析笔记

    ArrayList源码分析笔记 先贴出ArrayList一些属性 public class ArrayList<E> extends AbstractList<E> imple ...

  6. 线程池之ThreadPoolExecutor线程池源码分析笔记

    1.线程池的作用 一方面当执行大量异步任务时候线程池能够提供较好的性能,在不使用线程池的时候,每当需要执行异步任务时候是直接 new 一线程进行运行,而线程的创建和销毁是需要开销的.使用线程池时候,线 ...

  7. Android源码分析笔记--Handler机制

    #Handler机制# Handler机制实际就是实现一个 异步消息循环处理器 Handler的真正意义: 异步处理 Handler机制的整体表述: 消息处理线程: 在Handler机制中,异步消息处 ...

  8. ROCKETMQ源码分析笔记1:tools

    rocketmq源码解析笔记 大家好,先安利一下自己,本人男,35岁,已婚.目前就职于小资生活(北京),职位是开发总监. 姓名DaneBrown 好了.我保证本文绝不会太监!转载时请附上以上安利信息. ...

  9. 【TencentOS tiny】深度源码分析(4)——消息队列

    消息队列 在前一篇文章中[TencentOS tiny学习]源码分析(3)--队列 我们描述了TencentOS tiny的队列实现,同时也点出了TencentOS tiny的队列是依赖于消息队列的, ...

随机推荐

  1. UVA 10037 贪心算法

    题目链接:http://acm.hust.edu.cn/vjudge/contest/122829#problem/A 题目大意:N个人夜里过河,总共只有一盏灯,每次最多过两个人,然后需要有人将灯送回 ...

  2. SSH-key密钥生成

    为了能够不用输入密码访问git库(github/gitlab),需要使用ssh key ssh-keygen -t rsa -C "<your email address>&qu ...

  3. jQuery 幻灯片 ----摘录

    Cloud Carousel (演示 | 下载) ShineTime (演示 | 下载) Nivo Slider (演示 | 下载) Interactive Photo Desk (演示 | 下载) ...

  4. iOS应用崩溃日志分析-备用

    作为一名应用开发者,你是否有过如下经历?   为确保你的应用正确无误,在将其提交到应用商店之前,你必定进行了大量的测试工作.它在你的设备上也运行得很好,但是,上了应用商店后,还是有用户抱怨会闪退 ! ...

  5. cs代码实现控件移动TranslateTransform

    xaml: <Rectangle> <Rectangle.RenderTransform> <TranslateTransform x:Name="myTran ...

  6. 来,试试PERL

    试试,看看能否真的替代AWK,SED这些的... #!/usr/bin/perl print "hello, world!\n"; $line = <STDIN>; i ...

  7. 由于 UNION ALL Chinese_PRC_CI_AS”之间的排序规则冲突,值的排序规则未经解析

    由于不同的表之间的排序规则不一样,在归并集合的 时候会出现排序问题. 只要在查询的列后面 声明结果列的排序规则保持一致即可:  SELECT b0.[CardCode] collate SQL_Lat ...

  8. 【转】Android Service完全解析,关于服务你所需知道的一切(下) ---- 不错

    原文网址:http://blog.csdn.net/guolin_blog/article/details/9797169 转载请注册出处:http://blog.csdn.net/guolin_bl ...

  9. Linux开发工具的使用

    1.   Linux开发工具的使用 Vim编译的使用 Gdb调试工具的使用 Makefile的编写 linux跟踪调试 SSH的使用 subversion的使用 1.   Linux开发工具的使用 V ...

  10. bzoj有趣的题目

    你会发现bzoj上好多题AC率高的让人不敢想象 其实是因为数据没发,所以被n个人水过了-- 1142 1167 1351 1354 1359 1482 2812 3056 1469 我有特殊的减少代码 ...