我有一個啓動線程的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管理鎖定生命期的關鍵部分。 –