【发布时间】:2012-10-18 16:32:07
【问题描述】:
我在 Windows XP 上使用 MinGW 4.6.2,我在 std::atomic 上遇到了一些奇怪的行为。 情况如下:
- 线程 A 创建一个 std::atomic 变量(以 T* 作为模板参数)。
- 线程 B 对其进行了修改。
- 线程 A 等待修改然后读取变量。
最终结果是线程A读取的值不是线程B设置的值。
如果我删除 std::atomic (将变量保存为指针),它会按预期工作。更有趣的是,如果我将模板参数设置为 unsigned long 并将指针与 T* 之间进行转换,它会按预期工作。
我正在使用赋值运算符来设置值和加载成员来获取值。
我是否错过了以 T* 作为参数的 std::atomic 应该如何工作,或者这是一种破坏行为?
编辑
一些代码
#include <boost/thread.hpp>
#include <atomic>
using namespace std;
void* vptr;
std::atomic<unsigned int> aui;
std::atomic<void*> aptr;
void foo()
{
vptr = (void*) 0x123;
aui = (unsigned int) 0x123;
aptr = (void*) 0x123;
}
int main(int argc, char* argv[])
{
boost::thread threadA;
vptr = nullptr;
aui = 0;
aptr = nullptr;
threadA = boost::thread(foo);
threadA.join();
cout << vptr << " " << (void*)aui.load() << " " << aptr.load();
return 0;
}
输出为:0x123 0x123 0x41d028
【问题讨论】:
-
不要描述代码,贴出来。
-
不要将指针投射到
unsigned long。使用std::uintptr_t,这就是它的用途。 -
"...如果我将模板参数设置为 unsigned long 并将指针与 T* 之间进行转换,它会按预期工作。"
标签: c++ concurrency c++11 mingw