Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This code seems to work, but have I used the InterlockedIncrement function correctly? The correct memory alignment of m_count is of my primary concern. Assume we're on a x86-64 system and compile a 64-bit application (in case that matters). By the way, for my actual purposes I can't declare m_count as a volatile long and then use InterlockedIncrement(&m_count); but it must be a pointer to data in 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;
};
like image 900
zeroes00 Avatar asked Dec 29 '22 04:12

zeroes00


1 Answers

The heap allocator already aligns returned addresses to the native platform word size. 4 bytes for x86, 8 bytes for x64. You are using long, 32-bit on either platform for MSVC. No need to jump through the _aligned_malloc() hoop.

like image 138
Hans Passant Avatar answered Dec 30 '22 16:12

Hans Passant