【发布时间】:2013-07-08 21:05:49
【问题描述】:
我正在实现一个非常轻量级的原子包装器,作为 Windows 的 C++ 中原始数据类型的学习练习,我有一些关于实现赋值运算符的简单问题。考虑以下两种实现:
// Simple assignment
Atomic& Atomic::operator=(const Atomic& other)
{
mValue = other.mValue;
return *this;
}
// Interlocked assignment
Atomic& Atomic::operator=(const Atomic& other)
{
_InterlockedExchange(&mValue, other.mValue);
return *this;
}
假设 mValue 是正确的类型,并且 Atomic 类将其作为成员。
- 线程安全的赋值运算符是否需要
_InterlockedExchange,还是简单的实现足以保证线程安全? - 如果简单赋值是线程安全的,那么是否还需要为这个类实现赋值运算符?编译器默认值就足够了,不是吗?
- 如果简单赋值在 Windows 中是线程安全的,那么它在其他平台中是否也是线程安全的?是否需要等效于
_InterlockedExchange才能保证其他平台上的线程安全?
【问题讨论】:
标签: c++ winapi atomic assignment-operator