如何从堆中为InterlockedIncrement函数分配正确的内存对齐?

zer*_*s00 3 c++ heap multithreading thread-safety memory-alignment

这段代码似乎有用,但我是否正确使用了InterlockedIncrement函数?m_count的正确内存对齐是我主要关心的问题.假设我们在x86-64系统上并编译一个64位应用程序(如果重要的话).顺便说一句,为了我的实际目的,我不能将m_count声明为volatile long,然后使用InterlockedIncrement(&m_count); 但它必须是指向堆中数据的指针.

#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;
};
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 5

堆分配器已将返回的地址与本机平台字大小对齐.x86为4个字节,x64为8个字节.您在任一平台上使用32位 MSVC.无需跳过_aligned_malloc()箍.