我可以创建一个线程安全的 std::atomic<vector<int>> 吗?

2023-06-05C/C++开发问题
1

本文介绍了我可以创建一个线程安全的 std::atomic<vector<int>> 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个函数需要执行 n=1000 次.这个函数进行蒙特卡罗风格的模拟并返回一个 int 作为结果.我想并行运行 nthreads=4.每当一个线程完成一个循环时,它应该将结果放入std::vector.因此,在 1000 个周期后,我有一个可以通过统计检查的 1000 个 int 向量.

I'm having a function that needs to be executed n=1000 times. This functions does a Monte Carlo style simulation and returns an int as the result. I'd like to run nthreads=4 in parallel. Whenever a thread finishes one cycle, it should put the result in a std::vector<int>. Thus, after 1000 cycles, I've a vector of 1000 ints that can be examined by statistics.

由于 std::vector 不是线程安全的,我想到了 std::mutex(这肯定会工作).

Since a std::vector is not thread-safe, I thought about std::mutex (which would surely work).

但是我想知道是否可以将向量声明为原子向量从而绕过互斥锁?是否可以有 std::atomic>?我可以在上面使用 push_back 等吗?

But I wonder if I can declare a vector to be atomic and thus get around mutexes? Is it possible to have a std::atomic<std::vector<int>>? And can I use push_back etc. on it?

推荐答案

你不需要.从多个线程访问 std::vector 是完全可以的,if

You don't need to. It is totally okay to access a std::vector from multiple threads, if

  • 你读取对象
  • 你写给不同的对象

因此,请确保创建一个大小为 n=1000 的向量,并根据您的线程编号(1 到 4)将元素 0-249、250-499 等分配给您的线程.

So just make sure, you create a vector of size n=1000 and depending on your thread number (1 to 4) you assign elements 0-249, 250-499 etc. to your threads.

所以你的每个线程都会计算 n/nthreads 个元素.

So each of your thread computes n/nthreads elements.

这篇关于我可以创建一个线程安全的 std::atomic<vector<int>> 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6