这段时间忙着整理代码,想写一个简单的封装库,所以这里的文字比较少,但代码比较简单应该比较好看懂。另外对我的代码有什么看法,错误的地方,请具体提出,我会非常感激,对于只会骂人的人请你哪儿凉快哪儿呆着去。
今天提供一个原子计数的类
///////////.H/////
#ifndef LGLIB_SYNCLOCK_H
#define LGLIB_SYNCLOCK_H
#if _MSC_VER>1000
#pragma once
#endif
#include <WINDOWS.H>
namespace lglib
{
/*!
* lg_AtomicCounter类提供了一个线程安全的整数计数器。AotomicCounter依赖于平
* 台是否提供“原子”整数操作。
*/
class __LGLIB__ lg_AtomicCounter
{
private:
int32 atomic;
public:
/*!
* 默认构造函数
*/
lg_AtomicCounter();
/*!
* 赋初值构造函数
*
* @param value 初始值
*/
lg_AtomicCounter(int value);
/*! 自增量运算。 */
int32 operator++(void);
/*! 自减量运算。 */
int32 operator--(void);
/*! 增量运算。 */
int32 operator+=( int change );
/*! 减量运算。 */
int32 operator-=( int change );
/*! 加法运算。 */
int32 operator+( int change );
/*! 减法运算。 */
int32 operator-( int change );
/*! 赋值运算。 */
int32 operator=(int value);
/*! 非运算。 */
bool operator!(void);
/*! 类型转换,将该类转换为int型量。 */
operator int32();
};
}
/////////////////////////.CPP////////////////////////////////
namespace lglib {
//---------------------------------------------------------------------------
// 默认构造函数
lg_AtomicCounter::lg_AtomicCounter()
{ atomic = 0; }
/*!
* 赋初值构造函数
*
* @param value 初始值
*/
lg_AtomicCounter::lg_AtomicCounter(int value)
{ atomic = value; }
/*! 自增量运算。 */
int32 lg_AtomicCounter::operator++(void)
{ return InterlockedIncrement( &atomic ); }
/*! 自减量运算。 */
int32 lg_AtomicCounter::operator--(void)
{ return InterlockedDecrement( &atomic ); }
//---------------------------------------------------------------------------
// 增量运算。
int32 lg_AtomicCounter::operator+=( int change )
{
InterlockedExchangeAdd( &atomic, change );
return atomic;
}
//---------------------------------------------------------------------------
// 减量运算
int32 lg_AtomicCounter::operator-=( int change )
{
InterlockedExchangeAdd( &atomic, -change );
return atomic;
}
/*! 加法运算。 */
int32 lg_AtomicCounter::operator+( int change )
{ return atomic + change; }
/*! 减法运算。 */
int32 lg_AtomicCounter::operator-( int change )
{ return atomic - change; }
/*! 赋值运算。 */
int32 lg_AtomicCounter::operator=(int value)
{ return InterlockedExchange(&atomic, value); }
/*! 非运算。 */
bool lg_AtomicCounter::operator!(void)
{ return ( atomic == 0 ) ? true : false; }
/*! 类型转换,将该类转换为int型量。 */
lg_AtomicCounter::operator int32()
{ return atomic; }
}