Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ port of AtomicLong.lazySet

Tags:

java

c++

atomic

I'm trying to port some Java code to Windows C++ and am confused about how to implement AtomicLong.lazySet(). The only information I can find talks about what it does but not how to implement it, and the available source code ends up in a private native library owned by Sun (sun.misc.Unsafe.class).

I currently just set a member variable to the passed parameter but I'm not sure if it's correct.

class AtomicLong
{
public:
    inline void LazySet(__int64 aValue)
    {
        // TODO: Is this correct?
        iValue = aValue;
    }

    inline void Set(__int64 aValue)
    {
        ::InterlockedExchange64(&iValue, aValue);
    }

private:
    __declspec(align(64)) volatile __int64 iValue;
};

I cannot use boost.

Edit: I'm compiling to x64 but perhaps solutions for 32-bit code would be of help to others.

I don't have access to C++11.

like image 885
James Avatar asked Aug 09 '12 16:08

James


1 Answers

C++11 contains an atomic library, and it is easy if you can use it:

class AtomicLong
{
public:
    inline void LazySet(int64_t aValue)
    {
        iValue.store(aValue, std::memory_order_relaxed);
    }
    inline void Set(int64_t aValue)
    {
        iValue.store(aValue);
    }
private:
    std::atomic<int64_t> iValue;
};
like image 139
nosid Avatar answered Oct 26 '22 05:10

nosid