Lockfree 习作:最多保存56个对象的简单容器

Posted by 翡翠小屋 on March 17, 2008

练习作品:

// 最多可以存放 56 个数值的容器
 template< typename T >
 class SafeValuePool
 {
 public:
  SafeValuePool() : _mark(0) {}
  uint8 lock()
  {
   for( ;; ){
    for( int i=0; i<56; ++i ){
     assert( (_mark & 0xFFFFFFFFFFFFFF00LL)== 0xFFFFFFFFFFFFFF00LL ); // _mark 的最后8位用来防止 ABA
     uint64 v=_mark;
     if(( v & (1LL << (i+8) )==0 ){
      uint64 n=(v | (1LL << (i+8))) + 1) & 0xFFFFFFFFFFFFFF7FLL;
      if( CAS2( &_mark, v, n ) )
       return i;
     }
    }
   }
  }
  T& operator[]( uint8 index )
  {
   return _pool[index];
  }

  bool test( uint8 index )
  {
   return (_mark & (1LL << (index+8))!=0);
  }

  void unlock( uint8 index )
  {
   do{
    uint64 v=_mark;
    uint64 n=(( v & ~( 1LL << index ) ) + 1 ) & 0xFFFFFFFFFFFFFF7FLL;
   }while( !CAS2( &_mark, v, n ) );
  }
 private:
  volatile uint64 _mark;
  T _pool[56];
 };