多线程访问共享对象的线程安全问题
大约 1 分钟
多线程访问共享对象的线程安全问题
void handler01(A* q)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
q->testA();
}
int main()
{
A* p = new A();
thread t1(handler01, p);
delete p;
t1.join(); // 等待线程t1执行完才会往下走
return 0;
}
我们可以发现当调用q->testA();
时,。 所,可以使用shared_ptr
和weak_ptr
,即
void handler01(weak_ptr<A> pw)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
// 重点在这里!!!!
shared_ptr<A> sp = pw.lock(); // 尝试提升为shared_ptr
if (sp != nullptr)
{
sp->testA();
}
else
{
cout << "A对像已被析构" << endl;
}
}
int main()
{
{
shared_ptr<A> p(new A());
thread t1(handler01, weak_ptr<A>(p));
// detach是使主线程不用等待子线程可以继续往下执行,但即使主线程终止了,子线程也不一定终止。
t1.detach();
}
std::this_thread::sleep_for(std::chrono::seconds(20));
return 0;
}
- 强弱智能指针在线程中,通过对象的资源计数 来 监测对象的生存状态。