根据上面的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__