想要一种有效的方法来交换C ++中的两个指针

编程入门 行业动态 更新时间:2024-10-25 06:31:51
本文介绍了想要一种有效的方法来交换C ++中的两个指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个指针,它们指向多线程C ++应用程序中的大图形对象。 我尝试每5分钟交换一次。哪种方法安全且性能最佳? C ++ 11 atomic<> 是一个不错的选择吗?

I have two pointers which point to a big graph object in a multi-threading C++ app. I try to swap them every 5 minutes. Which way is safe and has the best performance? Is C++11 atomic<> a good choice?

推荐答案

交换是否需要是原子的?也就是说,您是否需要保证另一个线程在交换时不能观察到它们具有相同的值?

Does the swap need to be atomic? i.e. do you need to guarantee that another thread cannot observe them both having the same value while swapping?

如果不需要保证交换是原子的,则只需使用两个 std :: atomic< T *> 对象,并使用临时对象交换它们:

If you don't need to guarantee the swap is atomic then just use two std::atomic<T*> objects and swap them using a temporary:

T* tmp = p1; p1 = p2.load(); p2 = tmp;

如果您需要交换是原子的,那么要在标准C ++中执行,就需要存储它们两者都使用相同的结构,因此可以在一个步骤中进行更新,例如

If you need the swap to be atomic then to do it in standard C++ you will need to store them both in the same structure, so it can be updated in a single step e.g.

struct TwoPointers { T* p1; T* p2; } std::atomic<TwoPointers> p;

然后您可以像这样交换它们:

then you can swap them like so:

auto old = p.load(); p = { old.p2, old.p1 };

这使用双字原子操作,该操作可能在幕后使用互斥量实现,因此通过临时的简单分配可能会更好,但是我怀疑每五分钟一次会有什么区别。

This uses double-word atomic operations, which might be implemented with a mutex behind the scenes, so the simple assignment via a temporary is likely to perform better, but I doubt it will make any difference once every five minutes.

以上两个版本都假定只有一个线程会尝试交换因为尽管加载旧值是原子完成的,而写入新值是原子完成的,但在这两个步骤之间都有一个窗口,在此期间另一个线程可以更改指针值。如果这是一个问题,请使用 std :: atomic< TwoPointers> 代替:

Both versions above assume only one thread will try to swap them at any time, because although loading the old value is done atomically, and writing the new value is done atomically, there is a window between those two steps during which another thread could change the pointer values. If that's a problem use a std::atomic<TwoPointers> like this instead:

auto old = p.load(); while (!ppare_exchange_strong(old, { old.p2, old.p1 })) { };

在循环中使用 compare_exchange_strong 稍慢而不是单个原子存储,但是如果差异每五分钟发生一次,您将不会注意到差异。

Using compare_exchange_strong in a loop is slightly slower than a single atomic store, but again you won't notice the difference if it only happens once every five minutes.

This TwoPointers 解决方案还意味着两个指针共享一个缓存行,但是如果它们每隔五分钟是只读的,那么交换就不是问题。

This TwoPointers solutions also mean the two pointers share a cache-line, but if they are read-only apart from the swap every five minutes then that's not a problem.

更多推荐

想要一种有效的方法来交换C ++中的两个指针

本文发布于:2023-10-22 23:07:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法来   指针   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!