一份简易的Ring Buffer实现 #ifndef RINGBUF_H_INCLUDED_ #define RINGBUF_H_INCLUDED_ #include <windows.h> #include <assert.h> template <bool THREADSAFE> class ringbuflock { public: void lock() {} void unlock() {} }; template <> class ringbuflock<true> { public: ringbuflock() { InitializeCriticalSection(&m_cs); } ~ringbuflock() { DeleteCriticalSection(&m_cs); } void lock() { EnterCriticalSection(&m_cs); } void unlock() { LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION m_cs; }; template <class Lockable> class autolock { public: autolock(Lockable& lockable) : m_lockable(lockable) { m_lockable.lock(); } ~autolock() { m_lockable.unlock(); } private: Lockable& m_lockable; }; /* ** T必须有默认构造函数 */ template <class T, int SIZE, bool THREADSAFE=true> class ringbuf { public: typedef autolock<ringbuflock<THREADSAFE> > AutoLock; ringbuf() { m_posread = m_poswrite = 0; } void read(T& data) { assert (!empty()); AutoLock al__(m_lock); data = m_buf[m_posread++]; m_posread %= (SIZE+1); } void write(const T data) { assert(!full()); AutoLock al__(m_lock); m_buf[m_poswrite++] = data; m_poswrite %= (SIZE+1); } bool empty() const { AutoLock al__(m_lock); return m_posread == m_poswrite; } bool full() const { AutoLock al__(m_lock); return m_posread == (m_poswrite+1) % (SIZE+1); } private: T m_buf[SIZE+1]; /* 多出来的一个Slot用于区分空还是满*/ int m_posread; int m_poswrite; mutable ringbuflock<THREADSAFE> m_lock; }; #endif // RINGBUF_H_INCLUDED_ // 测试文件 #include "ringbuf.h" #include <stdio.h> void main() { ringbuf<int, 5, true> rb; int i=0; int ii; while (!rb.full()) { rb.write(i++); } while (!rb.empty()) { rb.read(ii); printf("%d", ii); } }