C++20 中的原子智能指针和互斥锁 [英] atomic smart pointers and mutex in C++20

查看:62
本文介绍了C++20 中的原子智能指针和互斥锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想从多个线程写入/读取一个对象,即使我在 C++11 中使用 shared_pointer,我也必须使用额外的互斥锁来保证线程安全.如果我使用 C++20 中引入的 atomic_shared_pointer,这仍然适用吗?

If I want to write/read to an object from multiple threads I have to use an additional mutex for thread safety even if I use shared_pointer in C++11. Does this still apply if I use atomic_shared_pointer introduced in C++20?

问候

推荐答案

在考虑 shared_ptr 的原子性时,可以考虑三层.

There are three layers one might consider when thinking about the atomicity of shared_ptr.

  1. 引用计数的原子性.也就是说,您在不同的线程上有两个 shared_ptr 对象,但它们都访问相同的托管引用计数.当您在一个线程上复制一个 shared_ptr 并删除引用相同引用计数的另一个 shared_ptr 时会发生什么?

  1. Atomicity of the reference count. That is, you have two shared_ptr objects on different threads, but they both access the same managed reference count. What happens when you copy one shared_ptr on one thread and delete a different shared_ptr that references the same reference count?

shared_ptr 在这些情况下提供了对抗竞争条件的保证.shared_ptr 的不同实例的引用计数上的数据竞争永远不会发生.

shared_ptr provides a guarantee against race conditions in these cases. Data races on the reference count for different instances of a shared_ptr never happen.

shared_ptr 对象本身的原子性.也就是说,您有一个 shared_ptr 对象,它被不同的线程引用.一个线程可能想要替换 shared_ptr 的存储对象或其他东西,但此时其他人可能正在访问它.

Atomicity of the shared_ptr object itself. That is, you have one shared_ptr object which is referenced by different threads. One thread may want to replace the shared_ptr's stored object or something, but someone else may be accessing it at that moment.

atomic 处理这种情况.如果对象是atomic,那么你可以通过通常的atomic界面玩这些游戏.

atomic<shared_ptr> deals with this case. If the object is an atomic<shared_ptr>, then you can play these games through the usual atomic interface.

shared_ptr指向事物的原子性.在这种情况下,多个线程可能使用多个不同的 shared_ptr 对象,但所有这些 shared_ptr 对象都指向同一个对象.而那些线程想要访问它们所指向的对象.

Atomicity of the thing pointed to by a shared_ptr. In this case, multiple threads may be using multiple different shared_ptr objects, but all of these shared_ptr objects point to the same object. And those threads want to access the object being pointed to by them.

这个原子性全靠你.shared_ptr 的原子性保证是关于对指针 的访问,而不是它指向的内容.如果您需要同步访问所指向的内容,则必须自己构建.

This atomicity is all on you. shared_ptr's atomicity guarantees are about accesses to the pointer, not what it points to. If you need synchronized access to what is being pointed to, you will have to build that yourself.

这篇关于C++20 中的原子智能指针和互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆