是否可以在C ++中创建原子向量或原子数组? [英] Is it possible to create an atomic vector or array in C++?

查看:129
本文介绍了是否可以在C ++中创建原子向量或原子数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,该代码在每秒激活的线程中使用一个int(int[])数组.

I have some code which uses an array of int (int[]) in a thread which is activated every second.

我使用std::mutex中的lock()将这个数组锁定在该线程中.

I use lock() from std::mutex to lock this array in this thread.

但是我想知道是否有一种方法可以创建原子数组(或向量)来避免使用互斥锁?我尝试了几种方法,但是编译器总是以某种方式抱怨?

However I wonder if there is a way to create an atomic array (or vector) to avoid using a mutex? I tried a couple of ways, but the compiler always complains somehow?

我知道有一种创建原子数组的方法,但这并不相同.

I know there is a way to create an array of atomics but this is not the same.

推荐答案

在实践中,在CPU级别上,有一些指令可以原子地更新int,好的编译器将这些指令用于std::atomic<int>.相反,没有指令可以原子地更新ints向量(对于我所知道的任何体系结构),因此 got 在某处是某种互斥体.您最好将其用作互斥体.

In practice, at the CPU level, there are instructions which can atomically update an int, and a good compiler will use these for std::atomic<int>. In contrast, there are are no instructions which can atomically update a vector of ints (for any architecture I am aware of), so there has got to be a mutex of some sort somewhere. You might as well let it be your mutex.

对于尚未使用互斥锁编写代码的未来读者:

For future readers who haven't yet written code with the mutex:

您无法创建int[10]std::atomic,因为这会导致返回数组的函数-您将无法获得这些数组.您可以执行的操作是拥有一个std::atomic<std::array<int,10>>

You can't create a std::atomic of int[10], because that leads to a function which returns an array - and you can't have those. What you can do, is have a std::atomic<std::array<int,10>>

int main()
{
  std::atomic<std::array<int,10>> myArray;
}

请注意,编译器/库将在内部创建一个互斥体以使其原子化.还要注意,这并不能满足您的需求.它允许您自动设置整个数组的值.

Note that the compiler/library will create a mutex under the hood to make this atomic. Note further that this doesn't do what you want. It allows you to set the value of the whole array atomically.

不允许,您不能读取整个数组,更新一个元素并以原子方式写回整个数组.

It doesn't allow you to read the whole array, update one element, and write the whole array back atomically.

读取和写入将分别是原子的,但是另一个线程可以进入读取和写入之间.

The reads and the writes will be individually atomic, but another thread can get in between the read and the write.

您需要互斥锁!

这篇关于是否可以在C ++中创建原子向量或原子数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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