无锁机制的循环缓冲技术

 

此技术是借鉴了Linux内核源代码技术,无锁应用条件是同时只有一个写线程和读线程访问缓冲区时,不用加互斥锁,因为读写两个计数器各不影响,除此以外,还是要加互斥锁,如写线程只有一个线程,读线程有N个同时访问,那么写端不用加,只在读端加互斥锁即可。

主要就两个方法:
unsigned int CRingBuffer::GetBuffer(unsigned char *pBuffer, unsigned int iSize)
{
unsigned int iLen;
iSize = min(iSize, m_WritePtr - m_ReadPtr);
/* first get the data from m_ReadPtr until the end of the pBuffer */
iLen = min(iSize, m_Size - (m_ReadPtr & (m_Size - 1)));
memcpy(pBuffer, m_Buffer + (m_ReadPtr & (m_Size - 1)), iLen);
/* then get the rest (if any) from the beginning of the pBuffer */
memcpy(pBuffer + iLen, m_Buffer, iSize - iLen);
m_ReadPtr += iSize;
return iSize;
}
unsigned int CRingBuffer:PutBuffer(unsigned char *pBuffer, unsigned int iSize)
{
unsigned int iLen;
iSize = min(iSize, m_Size - m_WritePtr + m_ReadPtr);
/* first put the data starting from m_WritePtr to pBuffer end */
iLen = min(iSize, m_Size - (m_WritePtr & (m_Size - 1)));
memcpy(m_Buffer + (m_WritePtr & (m_Size - 1)), pBuffer, iLen);
/* then put the rest (if any) at the beginning of the pBuffer */
memcpy(m_Buffer, pBuffer + iLen, iSize - iLen);
m_WritePtr += iSize;
return iSize;
}

只要保证一个线程读,一个线程写,就不用锁。
其实质就是让某一端保持一个线程在操作,例如:

1、如果写端只有一个线程,读线程有N个同时访问,那么写端不用加,只在读端加互斥锁即可;
2、如果读端只有一个线程,写线程有N个同时访问,那么读端不用加,只在写端加互斥锁即可。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值