programming/programming general

[C++] Atomic class 구현

Roien 2015. 7. 4.
반응형



#ifndef __UTIL_ATOMIC_HPP_201507__
#define __UTIL_ATOMIC_HPP_201507__


//--------------------------------------------------------------
// DEPENDENCIES
//--------------------------------------------------------------
#include <pthread.h>
#include "utilLog.hpp"

#if (true == HUB_OPT_TEST_PLATFORM_TYPE_ANDROID)
#include <cutils/log.h>
#endif


//--------------------------------------------------------------
// MACRO
//--------------------------------------------------------------

#define COMPARE_ATOMIC(_op_) \
    inline bool operator _op_ (const utilAtomic<TYPE> &ref) const { \
        return mValue _op_ ref.mValue; \
    } \
    inline bool operator _op_ (const TYPE *ref) const { \
        return mValue _op_ mValue; \
    }


//--------------------------------------------------------------
// CLASS DEFINITION
//--------------------------------------------------------------

template <typename TYPE>
class utilAtomic {
public:
    utilAtomic() {
        pthread_mutex_init(&mLock, (const pthread_mutexattr_t *) NULL);
    }

    ~utilAtomic() {
        pthread_mutex_destroy(&mLock);
    }

    utilAtomic<TYPE>& operator+(const utilAtomic<TYPE> &other);
    const utilAtomic<TYPE>& operator++(void) const;
    const utilAtomic<TYPE>& operator--(void) const;

    const utilAtomic& operator=(const TYPE &other);
    bool operator==(const TYPE &other) const;

    TYPE getValue() const {
        return mValue;
    }

    COMPARE_ATOMIC(==)
    COMPARE_ATOMIC(!=)
    COMPARE_ATOMIC(>)
    COMPARE_ATOMIC(<)
    COMPARE_ATOMIC(<=)
    COMPARE_ATOMIC(>=)


private:
    mutable pthread_mutex_t  mLock;
    mutable TYPE mValue;
};


template <typename TYPE>
utilAtomic<TYPE>& utilAtomic<TYPE>::operator+(const utilAtomic<TYPE> &other)
{
    pthread_mutex_lock(&mLock);
    this->mValue += other.mValue;
    pthread_mutex_unlock(&mLock);
    return *this;
}

template <typename TYPE>
const utilAtomic<TYPE>& utilAtomic<TYPE>::operator++(void) const
{
    pthread_mutex_lock(const_cast<pthread_mutex_t *>(&mLock));
    this->mValue++;
    pthread_mutex_unlock(const_cast<pthread_mutex_t *>(&mLock));
    return *this;
}

template <typename TYPE>
const utilAtomic<TYPE>& utilAtomic<TYPE>::operator--(void) const
{
    pthread_mutex_lock(const_cast<pthread_mutex_t *>(&mLock));
    this->mValue--;
    pthread_mutex_unlock(const_cast<pthread_mutex_t *>(&mLock));
    return *this;
}

template <typename TYPE>
const utilAtomic<TYPE>& utilAtomic<TYPE>::operator=(const TYPE &other)
{
    pthread_mutex_lock(const_cast<pthread_mutex_t *>(&mLock));
    this->mValue = other;
    pthread_mutex_unlock(const_cast<pthread_mutex_t *>(&mLock));
    return *this;
}

template <typename TYPE>
bool utilAtomic<TYPE>::operator==(const TYPE &other) const
{
    bool ret = false;
    if (this->mValue == other)
        ret = true;
    return ret;
}


#endif  // __UTIL_ATOMIC_HPP_201507__
// EOF



반응형

댓글