多线程无锁(lock-free) 堆的实现
2010-06-18 15:22
381 查看
堆的多线程化处理比较简单,它只有一个指向堆顶的变量需要竞争,因此我们可以很方便的用 cas 操作来完成。
代码来自我们正准备开源的 C++ 库,开发代号 lugce。
不明白什么是 lockfree 算法的可以参考我的这篇博文:http://blog.csdn.net/jadedrip/archive/2007/08/08/1731554.aspx
/* * Copyright (C) 2010 Chen Wang ( China ) * Email: jadedrip@gmail.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "lockfree.hpp" #if !defined(_MSC_VER) || (_MSC_VER < 1600) # define nullptr NULL #endif namespace lichc { namespace lockfree { static_assert(sizeof(void *) == 4, "64-bit code generation is not supported."); template< typename T > class queue { public: queue<T>() { _head.data=0; } void push( const T t ) { data* n=new data; n->value=t; int64 old,x; do{ old=_head.data; n->next=reinterpret_cast<data*>(old); // 高 32 位加一,这是为了处理 ABA 问题;低32位保存下一个对象的指针。 x=( old + 0x100000000LL ) & 0xFFFFFFFF00000000LL | reinterpret_cast<int32>(n); }while( !atomic_cas( &_head, old, x ) ); } bool pop( T& v ) { int64 old,x; data *olddata; do{ old=_head.data; if( (old & 0xFFFFFFFFLL) == 0 ) return false; olddata=reinterpret_cast<data*>( old ); x=( old + 0x100000000LL ) & 0xFFFFFFFF00000000LL | reinterpret_cast<int32>(olddata->next); }while( !atomic_cas( &_head, old, x ) ); v=olddata->value; delete olddata; return true; } private: struct data { data* next; // Next Node, nullptr for end. T value; }; private: atomic_int64 _head; }; }; };
代码来自我们正准备开源的 C++ 库,开发代号 lugce。
不明白什么是 lockfree 算法的可以参考我的这篇博文:http://blog.csdn.net/jadedrip/archive/2007/08/08/1731554.aspx
相关文章推荐
- 多线程无锁(lock-free)队列(queue)的实现探讨
- Java多线程之~~~ReadWriteLock 读写分离的多线程实现
- 多线程之间实现通讯,join,yield,lock
- 利用readwritelock简单模拟实现多线程下cache的系统
- java中多线程模拟(多生产,多消费,Lock实现同步锁,替代synchronized同步代码块)
- Java多线程之~~~ReadWriteLock 读写分离的多线程实现
- 多线程下Lock、Level-Lock、Lock-Free、ReaderWriterLock、ReaderWriterLockSlim性能比较
- Java5 多线程(三)--Lock和Condition实现线程同步通信
- Java5 多线程(三)--Lock和Condition实现线程同步通信
- MemoryPool的LockFree实现
- Java:多线程,使用同步锁(Lock)时利用Condition类实现线程间通信
- Java5 多线程(三)--Lock和Condition实现线程同步通信
- JAVA多线程(五)用lock、synchronized、阻塞队列三种方法实现生产者消费者模式
- java多线程---顺序打印ABC的三种实现---ReentrantLock方式
- MemoryPool的LockFree实现
- java多线程解说【玖】_锁实现:LockSupport工具类
- C++多线程笔记:使用std::lock_guard实现对共享数据的保护
- Java5 多线程(三)--Lock和Condition实现线程同步通信
- 07____多线程实现线程通信(Lock和Condition)
- Lock-Free的栈实现及与加锁实现的性能对比