在这个例子中,Counter类的对象由std::shared_ptr管理,并在多个线程中共享,在thread_func函数中,每次调用counter->increment()前,都用std::lock_guard<std::mutex>锁定mtx,保证每次访问increment()是原子操作,std::lock_guard是RAII风格的锁管理器,它会在代码块结束时自动释放锁。启动 10 个线程,每个线程对共享计...
<< std::endl; } private: std::string strData="测试数据"; bool valid; // 用于检查对象是否有效 void read() { auto self = shared_from_this(); //这可以延长this的声明周期 //auto self =this; // 这样会有问题 std::thread([self]() { std::this_thread::sleep_for(std::chrono::second...
std::shared_ptr<int> ptr = std::make_shared<int>(42); std::thread t1(worker, std::ref(ptr)); std::thread t2(worker, std::ref(ptr)); t1.join(); t2.join(); return 0; } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 在这个...
线程执行完毕后,main()函数将打印global_instance(std::shared_ptr对象)的值。 #include <iostream> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <vector> std::shared_ptr<int> global_instance = std::make_shared<int>(0); std::mutex m; constexpr int max_l...
std::cout<<"Thread: "<<std::this_thread::get_id()<<", Value: "<<*ptr<<std::endl; } 这是每个线程要执行的函数。它接受一个类型为std::shared_ptr<int>的参数,并打印当前线程 ID 和共享数据的值。 主函数: intmain(){ std::shared_ptr<int>sharedPtr=std::make_shared<int>(100); ...
//In thread 1 shared_ptr<myClass> private = global; ... //In thread 2 global = make_shared<myClass>(); ... 在这种情况下,我可以确定线程 1private将具有原始值global或线程 2 分配的新值,但无论哪种方式,它都会有一个有效的 shared_ptr 到 myClass?
std::this_thread::sleep_for(std::chrono::seconds(1)); //赋值操作, shared_ptr引用计数use_cont加1(c++11中是原子操作) std::shared_ptr<Test> lp = p; { //static变量(单例模式),多线程同步用 staticstd::mutex io_mutex; //std::lock_guard加锁 ...
{ std::shared_ptr<Counter> counter = std::make_shared<Counter>(); std::thread t1([&]() { for (int i = 0; i < 1000; ++i) { counter->increment(); } }); std::thread t2([&]() { for (int i = 0; i < 1000; ++i) { counter->...
{ static std::mutex io_mutex; std::lock_guard<std::mutex> lk(io_mutex); print("线程中的局部指针:", lp); } } int main() { std::shared_ptr<Base> p = std::make_shared<Derived>(); print("创建共享的 Derived (为 Base 指针)", p); std::thread t1{thr, p}, t2{thr, p}, ...
2.最后一个拥有该对象的shared_ptr通过operator=或reset()为其分配另一个指针。 2.std::shared_ptr使用实例分析 #include <iostream> #include <memory> #include <thread> #include <chrono> #include <mutex> struct Base { Base() { std::cout << " Base::Base()\n"; } // Note: non-virtual ...