【C++】强弱智能指针引起的线程安全问题

it2022-05-05  178

使用普通裸指针造成的问题

#include <iostream> #include <memory> #include <thread> using namespace std; class A { public: A() { cout << "A()" << endl; } ~A() { cout << "~A()" << endl; } void funA() { cout << "A的一个非常好用的一个方法" << endl; } }; void hander01(A *p) { std::this_thread::sleep_for(std::chrono::seconds(2)); p->funA(); } int main() { A *p = new A(); thread t1(hander01,p); delete p; t1.join(); }

运行结果:

A在析构完成之后还可以调用A的方法,这个操作是极其不安全的一个操作的,所以我们可以使用强弱智能指针来使得操作变得安全起来。

shared_ptr 和 weak_ptr的解决问题

#include <iostream> #include <memory> #include <thread> using namespace std; class A { public: A() { cout << "A()" << endl; } ~A() { cout << "~A()" << endl; } void funA() { cout << "A的一个非常好用的一个方法" << endl; } }; void handler01(weak_ptr<A> q) { //需要检测对象A是否存活 std::this_thread::sleep_for(std::chrono::seconds(2)); shared_ptr<A> ptmp = q.lock(); if (ptmp != nullptr) { ptmp->funA(); } else { cout << "A对象已经析构" << endl; } } int main() { { shared_ptr<A> p(new A()); thread t1(handler01, weak_ptr<A>(p)); t1.detach(); } std::this_thread::sleep_for(std::chrono::seconds(10)); }

运行结果:


最新回复(0)