根據上面的5個函數就能做出一個原子操作的整數數字類,這將是下一節中,我的最輕量級鎖的基礎和原型,他不依賴于操作系統,當然,所以你也可以不叫他是鎖,只是一種類似鎖的機制.
一切細節看源碼中穿插的注釋.
#ifndef __ATOM_VALUE_H__
#define __ATOM_VALUE_H__
#include "atom.hpp"
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
template<typename T>
class atomic_value32
{
//恩,用boost.type_traits來保證是位的整數類型
BOOST_STATIC_ASSERT(sizeof(T) == 4 && boost::is_integral<T>::value);
private:
volatile T value_;
public:
atomic_value32(T v = 0)
:value_(v){}
atomic_value32(atomic_value32& v){//??? 這里留給大家,我不給出源碼了
}
//需要這么一個轉型符號,因為大部分時候我們將atomic_value32<T>當作一個T使用
operator T(){return exchange_add32(&value_,0);}
//賦值
atomic_value32& operator=(T v){exchange32(&value_, v);return *this;}
atomic_value32& operator=(atomic_value32& v){exchange32(&value_, v);return *this;}
//比較并交換,好像沒有什么operator與之對應,就直接拿出來了
T compare_exchange(T to_exchange, T to_compare)
{return compare_exchange32<T>(&value_, to_exchange, to_compare);}
//只提供前置,后置似乎沒什么必要,我也懶得去實現了:)
T operator++(){return increment32(&value_);}
T operator--(){return decrement32(&value_);}
//千萬不能返回引用,因為線程安全考慮,
T operator+=(T add){return exchange_add32(&value_,add);}
T operator+=(atomic_value32& add){return exchange_add32(&value_,add);}
T operator-=(T add){return exchange_add32(&value_,-add);}
T operator-=(atomic_value32& add){return exchange_add32(&value_,-add);}
//6個比較符號
bool operator==(T rhs){return operator T()==rhs;}
bool operator==(atomic_value32& rhs){return operator T()==rhs.operator T();}
bool operator<(T rhs){return operator T()<rhs;}
bool operator<(atomic_value32& rhs){return operator T()<rhs.operator T();}
bool operator!=(T rhs){return !this->operator ==(rhs);}
bool operator!=(atomic_value32& rhs){return !this->operator ==(rhs);}
bool operator>=(T rhs){return !this->operator <(rhs);}
bool operator>=(atomic_value32& rhs){return !this->operator <(rhs);}
bool operator>(T rhs){return ((*this)!=(rhs)) && !((*this)<(rhs));}
bool operator>(atomic_value32& rhs){return ((*this)!=(rhs)) && !((*this)<(rhs));}
bool operator<=(T rhs){return !((*this)>(rhs));}
bool operator<=(atomic_value32& rhs){return !((*this)>(rhs));}
};
#endif//__ATOM_VALUE_H__