如何使用std :: atomic<>有效地用于非原始类型? [英] How to use std::atomic<> effectively for non-primitive types?

查看:145
本文介绍了如何使用std :: atomic<>有效地用于非原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: atomic<> 的定义

您应该避免在课堂上使用它吗?

When should you avoid using it for classes?

推荐答案

操作 std :: atomic 类型是基本的。你可以构造并销毁 atomic< T> ,你可以询问类型 is_lock_free()存储 T 的副本,您可以通过各种方式交换 T 的值。如果这对你的目的是足够的,那么你可能会比拥有一个明确的锁更好。

The operations std::atomic makes available on any trivially copyable type are pretty basic. You can construct and destroy atomic<T>, you can ask if the type is_lock_free(), you can load and store copies of T, and you can exchange values of T in various ways. If that's sufficient for your purpose then you might be better off doing that than holding an explicit lock.

如果这些操作不够,如果你需要原子直接对值执行序列操作,或者如果对象足够大,复制是昂贵的,那么相反,您可能希望保持一个显式锁,您管理该锁以实现更复杂的目标,或避免执行所有使用 atomic< T> 将涉及。

If those operations aren't sufficient, if for example you need to atomically perform a sequence operations directly on the value, or if the object is large enough that copying is expensive, then instead you would probably want to hold an explicit lock which you manage to achieve your more complex goals or avoid doing all the copies that using atomic<T> would involve.

// non-POD type that maintains an invariant a==b without any care for
// thread safety.
struct T { int b; }
struct S : private T {
    S(int n) : a{n}, b{n} {}
    void increment() { a++; b++; }
private:
    int a;
};

std::atomic<S> a{{5}}; // global variable

// how a thread might update the global variable without losing any
// other thread's updates.
S s = a.load();
S new_s;
do {
    new_s = s;
    new_s.increment(); // whatever modifications you want
} while (!a.compare_exchange_strong(s, new_s));

正如你所看到的,这基本上获得了一个值的副本,修改副本,然后尝试将修改的值复制回来,根据需要重复。您对副本所做的修改可以非常复杂,而不仅限于单个成员函数。

As you can see, this basically gets a copy of the value, modifies the copy, then tries to copy the modified value back, repeating as necessary. The modifications you make to the copy can be as complex as you like, not simply limited to single member functions.

这篇关于如何使用std :: atomic&lt;&gt;有效地用于非原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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