How to allocate correct memory alignment from the heap for the InterlockedIncrement function?

This code works, but did I use the InterlockedIncrement function correctly? Proper memory alignment m_count is my main concern. Suppose we are on an x86-64 system and compile a 64-bit application (if that matters). By the way, for my real purposes, I cannot declare m_count as durable, and then use InterlockedIncrement (& m_count); but it should be a pointer to the data on the heap.

#include <Windows.h>
#include <malloc.h>

class ThreadSafeCounter {
public:
    ThreadSafeCounter()
    {
        // Are those arguments for size and alignment correct?
        void* placement = _aligned_malloc( sizeof(long), sizeof(long) );
        m_count = new (placement) long(0);
    }
    ~ThreadSafeCounter()
    {
        _aligned_free( const_cast<long*>(m_count) );
    }

    void AddOne()
    {
        InterlockedIncrement(m_count);
    }

    long GetCount()
    {
        return *m_count;
    }

private:
    volatile long* m_count;
};
+3
source share
3 answers

. 4 x86, 8 x64. 32- MSVC. _aligned_malloc().

+5

, , , . ABI , , ( ) . malloc() , .

http://en.wikipedia.org/wiki/False_sharing - , ( sizeof(long)), , .

, / .

Microsoft __declspec(align(value)) . , , / , , pimpl - .

+3

- , .

, , MSVC shared_ptr.

    typename aligned_storage<sizeof(_Ty),
        alignment_of<_Ty>::value>::type _Storage;
    };
    _Ty *_Getptr() const {  // get pointer
        return ((_Ty *)&_Storage);
    }

This C-cast is pretty nasty. However, this tells me that this object will definitely have the correct alignment using features.

+1
source

Source: https://habr.com/ru/post/1777890/


All Articles