2020-10-18日学习智能指针shared_ptr 一个用法

***1.***关于共享智能指针shared_ptr 中 sharded_ptr p (new a)的使用是

#include “stdafx.h”
#include
#include
#include

using namespace std;
class Person
{
public:
Person(int v) {
value = v;
std::cout << “Cons” <<value<< std::endl;
}
~Person() {
std::cout << “Des” <<value<< std::endl;
}

int value;

};

int main()
{
std::shared_ptr p1(new Person(1));// Person(1)的引用计数为1

std::shared_ptr<Person> p2 = std::make_shared<Person>(2);

p1.reset(new Person(3));// 首先生成新对象,然后引用计数减1,引用计数为0,故析构Person(1)
                        // 最后将新对象的指针交给智能指针。此时的p1 指针就是指向person(3)

std::shared_ptr<Person> p3 = p1;//现在p1和p3同时指向Person(3),Person(3)的引用计数为2

p1.reset();//Person(3)的引用计数为1
p3.reset();//Person(3)的引用计数为0,析构Person(3)
return 0;

}
其实是
 reset()包含两个操作。当智能指针中有值的时候,调用reset()会使引用计数减1.当调用reset(new xxx())重新赋值时,智能指针首先是生成新对象,然后将就对象的引用计数减1(当然,如果发现引用计数为0时,则析构旧对象),然后将新对象的指针交给智能指针保管。

2 C++11 thread 要注意join的位置一般放入最后

3 std::condition_variable: 是条件变量作用与对线程进行阻塞。典型按理生产者和消费者模式。其工作原理配合函数notify_all () wait() 等函数使用。相当于通过信号唤醒阻塞的一种方式。一定要配合std::unique_lock 锁进行使用。因为在使用wait 进行阻塞线程的时候只能锁的来自动开锁和闭锁。而unique_lock 是能管理开锁和闭锁的所以适合给wait() 和notify_all 使用。整个阻塞过程是
当前线程调用wait函数后阻塞(此时当前线程获得了锁(mutex ), 假设是lck), 只到另外某个线程调用notify_one或者notify_all唤醒当前线程程被阻塞时,该函数会自动调用lck.unlock()释放锁, 使得其他被阻塞在锁竞争上的线程得锁,以继续执行。另外, 一 旦当前线程得通知, wait函数也是自动调用Ick.lock() , 使得lck的状态和wait函数被调用时相同.
典型例子:
#include // std::thread

#include // std::mutex, std::unique_lock

#include <condition_variable> // std::condition_variable

std::mutex mtx; // 全局互斥锁.

std::condition_variable cv; // 全局条件变量.

bool ready = false; // 全局标志位.

void do_print_id(int id)

{

std::unique_lock <std::mutex> lck(mtx);

while (!ready) // 如果标志位不为 true, 则等待...

    cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,

// 线程被唤醒, 继续往下执行打印线程编号id.

std::cout << "thread " << id << '\n';

}

void go()

{

std::unique_lock <std::mutex> lck(mtx);

ready = true; // 设置全局标志位为 true.

cv.notify_all(); // 唤醒所有线程.

}

int main()

{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(do_print_id, i);
std::cout << “10 threads ready to race…\n”;

go(); // go!

for (auto & th:threads)
th.join();

return 0;

}

结果:

thread 1

thread 0

thread 2

thread 3

thread 4

thread 5

thread 6

thread 7

thread 8

thread 9

4 unique_lock比lock_guard占用空间和速度慢一些其有

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值