双缓存静态循环队列(三)

 1 // TwoBufQueue.h: interface for the CTwoBufQueue class.
 2 //
 3 //////////////////////////////////////////////////////////////////////
 4 
 5 #if !defined(AFX_TWOBUFQUEUE_H__EA19608F_9562_4803_95C4_5C4A574CC928__INCLUDED_)
 6 #define AFX_TWOBUFQUEUE_H__EA19608F_9562_4803_95C4_5C4A574CC928__INCLUDED_
 7 
 8 #if _MSC_VER > 1000
 9 #pragma once
10 #endif // _MSC_VER > 1000
11 #include "BufQueue.h"
12 
13 // 双缓存队列,减少读写操作的互斥碰撞,向无锁算法靠近,乒乓存储原理
14 
15 /* 
16 1)对于读写双方读写操作你比较频繁,双方的的瞬时吞吐量存在差异,可以很好的利用缓存空间特性提读写效率。
17 
18 2)消费数据的速度总是大于生产数据的的速度,本数据结构与单缓存队列无异。
19 
20 3)可以减少了读写互斥消耗,同时读,同时写互斥仍存在。
21 */
22 
23 class CTwoBufQueue  
24 {
25 public:
26     int GetdataSize();
27     int Write(const char *pBuf, int writeBytes);
28     int Read(char *pBuf, int readBytes);
29     CTwoBufQueue();
30     virtual ~CTwoBufQueue();
31 private:
32     void private_SwitchPointer();
33     CBufQueue m_Queue_A;
34     CBufQueue m_Queue_B;
35     CBufQueue *m_pRead_Q;
36     CBufQueue *m_pWrite_Q;
37     CCritcalS m_critcal;
38 };
39 
40 #endif // !defined(AFX_TWOBUFQUEUE_H__EA19608F_9562_4803_95C4_5C4A574CC928__INCLUDED_)
CTwoBufQueue_H
 1 // TwoBufQueue.cpp: implementation of the CTwoBufQueue class.
 2 //
 3 //////////////////////////////////////////////////////////////////////
 4 
 5 #include "stdafx.h"
 6 #include "OverlapRoutine.h"
 7 #include "TwoBufQueue.h"
 8 
 9 #ifdef _DEBUG
10 #undef THIS_FILE
11 static char THIS_FILE[]=__FILE__;
12 #define new DEBUG_NEW
13 #endif
14 
15 //////////////////////////////////////////////////////////////////////
16 // Construction/Destruction
17 //////////////////////////////////////////////////////////////////////
18 
19 CTwoBufQueue::CTwoBufQueue()
20 {
21      this->m_pRead_Q = &m_Queue_A;
22      this->m_pWrite_Q = &m_Queue_B;
23 }
24 
25 CTwoBufQueue::~CTwoBufQueue()
26 {
27 
28 }
29 
30 // 交换缓存对象指针
31 void CTwoBufQueue::private_SwitchPointer()
32 {
33     CBufQueue *pTemp = this->m_pRead_Q;
34     this->m_pRead_Q = this->m_pWrite_Q;
35     this->m_pWrite_Q = pTemp;
36 }
37 
38 int CTwoBufQueue::Read(char *pBuf, int readBytes)
39 {
40     int res = this->m_pRead_Q->Read(pBuf,readBytes);
41     if(res>0)
42     {
43         return res;
44     }else //读缓存空 ,交换缓存对象指针
45     {
46         this->m_critcal.Lock();
47         this->private_SwitchPointer();
48         this->m_critcal.Free();
49 
50         return this->m_pRead_Q->Read(pBuf,readBytes);
51     }
52 }
53 
54 // 写操作指针对当前buf对象,不做交换
55 int CTwoBufQueue::Write(const char *pBuf, int writeBytes)
56 {
57     this->m_critcal.Lock();
58     int res = this->m_pWrite_Q->Write(pBuf,writeBytes);
59     this->m_critcal.Free();
60 
61     return res;
62 }
63 
64 int CTwoBufQueue::GetdataSize()
65 {
66     return this->m_pRead_Q->GetdataSize()+this->m_pWrite_Q->GetdataSize();
67 }
CTwoBufQueue_CPP
原文地址:https://www.cnblogs.com/Esperanto/p/5353996.html