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()
{
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;
};
source
share