【发布时间】:2015-09-05 23:33:05
【问题描述】:
我有一个启动线程的 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 管理锁生命周期的关键部分。
标签: c++ multithreading visual-c++ mfc atl