zer*_*s00 3 c++ heap multithreading thread-safety memory-alignment
这段代码似乎有用,但我是否正确使用了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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1697 次 |
| 最近记录: |