智能指针5
-
多线程访问共享对象的安全问题
#include <chrono> # include <iostream> # include <memory> # include <thread> class A{ public: A() { std::cout << "A()" << std::endl; } ~A() { std::cout << "~A()" << std::endl; } void func() { std::cout << "do sth" << std::endl; } }; void handler(std::weak_ptr<A> wp) { std::this_thread::sleep_for(std::chrono::seconds(2)); std::shared_ptr<A> sp = wp.lock(); if (sp) { sp->func(); } else { std::cout << "not callable" << std::endl; } } int main() { { std::shared_ptr<A> sp = std::make_shared<A>(); std::thread t1(handler, std::weak_ptr(sp)); // 注意要传入weak_ptr t1.detach(); } getchar(); return 0; }