简体   繁体   English

原子共享指针列表

[英]List of atomic shared pointers

I need a thread-safe list of shared pointers and I saw that in c++20 they added template specializations for the atomic shared _ptr.我需要一个线程安全的共享指针列表,我看到在 c++20 中他们为原子共享_ptr 添加了模板特化。 ( std::atomic<std::shared_ptr<Delegate>> ). std::atomic<std::shared_ptr<Delegate>> )。

I was thus wondering do I need to implement my own doubly-linked list or this is what I need std::list<std::atomic<std::shared_ptr<Delegate>>> for my thread-safe list?因此,我想知道我是否需要实现自己的双向链表,或者这就是我需要std::list<std::atomic<std::shared_ptr<Delegate>>>来创建线程安全列表?

A std::list<std::atomic<std::shared_ptr<Delegate>>> is a list of atomic pointers. std::list<std::atomic<std::shared_ptr<Delegate>>>是原子指针列表。 This means the pointers have some thread safety guarantees.这意味着指针有一些线程安全保证。

It is not an atomic list, nor does the list structure have any extra thread safety compared with the same structure with no std::atomic .它不是原子列表,与没有std::atomic的相同结构相比,列表结构也没有任何额外的线程安全性。

So for example if you have two threads which hold references to elements in the list, it is safe for one of them to modify the pointer and the other one to read it (the reader will see either the old or the new value).因此,例如,如果您有两个线程持有对列表中元素的引用,那么其中一个线程修改指针而另一个线程读取它是安全的(读者将看到旧值或新值)。

But if you modify the list (push, pop, clear, etc) in one thread while reading or modifying it in another thread, that's undefined behavior.但是,如果您在一个线程中修改列表(推送、弹出、清除等),同时在另一个线程中读取或修改它,这是未定义的行为。 For that you'd probably want to use a different, thread-safe container, or protect the std::list with a std::mutex .为此,您可能希望使用不同的线程安全容器,或使用std::mutex保护std::list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM