RingBuffer.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "stdafx.h"
  2. #ifdef CMD_ANSYNC
  3. #include "memory.h"
  4. #include "windows.h"
  5. #include "RingBuffer.h"
  6. CRingBuffer::CRingBuffer()
  7. {
  8. m_pObj = NULL;
  9. }
  10. int CRingBuffer::Init(int nObj, int nObjSize)
  11. {
  12. m_nObj = nObj;
  13. m_nObjSize = nObjSize;
  14. m_nInput = 0;
  15. m_nOutput = 0;
  16. m_pObj = new unsigned char[nObjSize * nObj];
  17. InitializeCriticalSection(&m_stCS);
  18. return 0;
  19. }
  20. int CRingBuffer::Fini()
  21. {
  22. if (NULL != m_pObj)
  23. delete m_pObj;
  24. return 0;
  25. }
  26. int CRingBuffer::Input(void * pObj)
  27. {
  28. return OPObj(1, pObj);
  29. }
  30. int CRingBuffer::Output(void * pObj)
  31. {
  32. return OPObj(0, pObj);
  33. }
  34. int CRingBuffer::OPObj(int nAction, void * pObj)
  35. {
  36. int nPos = -1;
  37. EnterCriticalSection(&m_stCS);
  38. if (0 == nAction)
  39. {
  40. if (m_nInput > m_nOutput)
  41. {
  42. nPos = m_nOutput % m_nObj;
  43. memcpy(pObj, (char *)m_pObj + m_nObjSize * m_nOutput, m_nObjSize);
  44. m_nOutput++;
  45. }
  46. }
  47. else
  48. {
  49. if (m_nInput - m_nObj < m_nOutput)
  50. {
  51. nPos = m_nInput % m_nObj;
  52. memcpy((char *)m_pObj + m_nObjSize * m_nOutput, pObj, m_nObjSize);
  53. m_nInput++;
  54. }
  55. }
  56. LeaveCriticalSection(&m_stCS);
  57. return nPos;
  58. }
  59. #endif