我有一个启动线程的MFC类,线程需要修改主类的CString成员。线程安全字符串读取/写入
我讨厌互斥锁,所以必须有一个更简单的方法来做到这一点。
我想使用boost.org库或atl :: atomic或shared_ptr变量。
什么是读写字符串和线程安全的最佳方法?
class MyClass
{
public:
void MyClass();
static UINT MyThread(LPVOID pArg);
CString m_strInfo;
};
void MyClass::MyClass()
{
AfxBeginThread(MyThread, this);
CString strTmp=m_strInfo; // this may cause crash
}
UINT MyClass::MyThread(LPVOID pArg)
{
MyClass pClass=(MyClass*)pArd;
pClass->m_strInfo=_T("New Value"); // non thread-safe change
}
根据MSDN shared_ptr的自动工作https://msdn.microsoft.com/en-us/library/bb982026.aspx
所以这是一个更好的方法?
#include <memory>
class MyClass
{
public:
void MyClass();
static UINT MyThread(LPVOID pArg);
std::shared_ptr<CString> m_strInfo; // ********
};
void MyClass::MyClass()
{
AfxBeginThread(MyThread, this);
CString strTmp=m_strInfo; // this may cause crash
}
UINT MyClass::MyThread(LPVOID pArg)
{
MyClass pClass=(MyClass*)pArd;
shared_ptr<CString> newValue(new CString());
newValue->SetString(_T("New Value"));
pClass->m_strInfo=newValue; // thread-safe change?
}
使用RAII管理锁定生命期的关键部分。 –