这段代码似乎有效,但我是否正确使用了 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;
};