c++ - How to allocate from heap with the correct memory alignment for InterlockedIncrement function? -
this code seems work, have used interlockedincrement function correctly? correct memory alignment of m_count of primary concern. assume we're on x86-64 system , compile 64-bit application (in case matters). way, actual purposes can't declare m_count volatile long , use interlockedincrement(&m_count); must pointer data in heap.
#include <windows.h> #include <malloc.h> class threadsafecounter { public: threadsafecounter() { // arguments size , 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; };
the heap allocator aligns returned addresses native platform word size. 4 bytes x86, 8 bytes x64. using long, 32-bit on either platform msvc. no need jump through _aligned_malloc() hoop.
Comments
Post a Comment