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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With