以为原子指针不会崩溃,但实际发生了,究其原因还是原子指针只能保证其自身是线程安全的,它不能保证它函数之外的代码可以线程安全。
class MyClassAtomic
{
public:
MyClassAtomic()
{
};
~MyClassAtomic()
{
};
static MyClassAtomic* instance()
{
static MyClassAtomic* pIns = nullptr;
if (pIns == nullptr)
{
pIns = new MyClassAtomic();
}
return pIns;
}
void setStr(std::string* pstr)
{
auto pPtrStr = new QSharedPointer<std::string>(pstr);
auto pOldStr = atomicPtr.fetchAndStoreRelaxed(pPtrStr);
delete pOldStr;
}
QSharedPointer<std::string> getStr()
{
return *atomicPtr.loadRelaxed();
}
private:
QAtomicPointer<QSharedPointer<std::string>> atomicPtr;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyClassAtomic::instance();
std::thread t1([]()
{
while (1)
{
std::string* s1 = new std::string("123");
MyClassAtomic::instance()->setStr(s1);
QSharedPointer<std::string> s1_1 = MyClassAtomic::instance()->getStr();
qDebug() << "t1 : " << QString::fromStdString(*s1_1);
}//~QSharedPointer()引发了异常: 读取访问权限冲突。
});
std::thread t2([]()
{
while (1)
{
std::string* s2 = new std::string("abc");
MyClassAtomic::instance()->setStr(s2);
QSharedPointer<std::string> s2_1 = MyClassAtomic::instance()->getStr();
qDebug() << "t2 : " << QString::fromStdString(*s2_1);
}
});
a.exec();
return 0;
}