无锁(lock-free)队列的一个简单实现
2008-03-06 14:18
561 查看
作为 无锁的 ( lock-free ) 线程安全算法 的一个习作吧。思想、算法十分简单。
这个队列的大小是固定的,很多情况下应该够用了。
#ifdef WIN32 inline void sleep( uint32 mil ) { Sleep( mil ); } inline bool CAS(void* pDest, uint32 cmp, uint32 xchg){ return InterlockedCompareExchange(reinterpret_cast<PLONG>(pDest), static_cast<LONG>(xchg), static_cast<LONG>(cmp)) == static_cast<LONG>(cmp); } inline int32 SafeInc(int32* pVal) { return static_cast<int32>(InterlockedIncrement(reinterpret_cast<PLONG>(pVal))); } inline int32 SafeDec(int32* pVal) { return static_cast<int32>(InterlockedDecrement(reinterpret_cast<PLONG>(pVal))); } #endif //这儿告诉编译器按照8字节对齐 #ifdef _MSC_VER # pragma pack(push, 8) #endif /* _MSC_VER */ template< typename T, int max_size=1024 > class Quese { public: Quese() { memset( _buf, 0, sizeof(T*) * max_size ); _begin=_end=0; _size=0; } void push( T* pVal ) { if( pVal==0 ) return; int32 cur; bool loop=true; do{ if ( _size == max_size ) { sleep( 1 ); // TODO: 扩展 continue; } cur=safe_move( &_end );; loop=!CAS( _buf + cur , 0, (uint32)pVal ); }while( loop ); SafeInc( (int32*)&_size ); } T * pop() { int32 cur; T *p; do{ if ( _size==0 ) return NULL; cur=safe_move( &_begin ); p= _buf[cur]; }while( p==0 || !CAS( _buf + cur, (uint32)p, 0 ) ); SafeDec( (int32*)&_size ); return p; } public: uint32 safe_move( volatile uint32* p ) { uint32 next; uint32 cmp; do{ cmp=*p; next=cmp+1; if( next >= max_size ) next=0; }while( !CAS( (uint32*)p, cmp, next ) ); return cmp; } T* _buf[max_size]; volatile uint32 _begin; volatile uint32 _end; volatile int32 _size; };
这个队列的大小是固定的,很多情况下应该够用了。
相关文章推荐
- 实现一个lockfree的队列——错误修改
- 实现一个lockfree 的队列
- Java编程的逻辑 (61) - 内存映射文件及其应用 - 实现一个简单的消息队列
- 使用 ReentrantLock 和 Condition 实现一个阻塞队列
- 一个简单的优先级队列实现
- 实现一个锁无关(lock free)结构~
- 简单题_用两个栈实现队列和用两个队列实现一个栈
- [转载] STL allocator的介绍和一个基于malloc/free的allocator的简单实现
- java多线程与并发 - 自己实现一个简单的锁(实现Lock接口)
- evpp性能测试(3): 对无锁队列boost::lockfree::queue和moodycamel::ConcurrentQueue做一个性能对比测试
- 请实现一个队列,既可以存放整数,又可以存放字符串。简单的说,队列是一种数据结构,按照先进先出的顺序管理进、出队列的元素
- 链表实现一个简单的队列
- 使用两个栈来实现一个队列简单的push和pop
- 简单算法 - 两个队列实现一个栈
- 请实现一个队列,既可以存放整数,又可以存放字符串。简单的说,队列是一种数据结构,按照先进先出的顺序管理进、出队列的元素
- 无锁队列的环形数组实现(Lock Free Queue Implementation in Ring Array)
- 循环队列的一个简单实现
- C#实现一个简单的工作队列调度器
- 一个简单的阻塞队列实现
- C语言实现一个最简单的队列