C++ p7,8

#include<iostream>
#include<memory>
#include<thread>
#include<chrono>
#include<mutex>

struct Base{
	Base(){std::cout<<"Base::Base()\n";}
	~Base(){std::cout<<"Base::Base()\n";}
};

struct Derived:public Base{
	Derived(){std::cout<<"Derived::Derived()\n";}
	~Derived(){std::cout<<"Derived::Derived()\n";}
};

void thr(std::shared_ptr<Base> p){
	std::this_thread::sleep_for(std::chrono::seconds(1));
	std::shared_ptr<Base> lp=p;{
		static std::mutex io_mutex;
		std::lock_guard<std::mutex>lk(io_mutex);
		std::cout<<"local pointer in a thread:\n"<<"lp.get()="<<lp.get()<<",lp.use_count()="<<lp.use_count()<<'\n';
	}
}
int main(){
	std::shared_ptr<Base>p=std::make_shared<Derived>();
	
	std::cout<<"Created a shared Derived(as a pointer to Base)\n"<<"p.get()="<<p.get()<<",p.use_count()="<<p.use_count()<<'\n';
	std::thread t1(thr,p),t2(thr,p),t3(thr,p);
	p.reset();
	std::cout<<"Shared ownership between 3 threads and released\n"<<"ownership from main:\n"<<"p.get()="<<p.get()<<",p.use_count="<<p.use_count()<<'\n';
	t1.join();
	t2.join();
	t3.join();
	std::cout<<"All threads completed,the last one deleted Derived\n";
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值