问题描述
我有一个需要执行的函数 n = 1000
次。此函数执行蒙特卡罗风格模拟,并返回 int
作为结果。我想同时运行 nthreads = 4
。每当一个线程完成一个周期,它应该把结果放在一个 std :: vector< int>
。
因此,在1000个周期后,我有一个1000 int
的向量,可以通过统计检查。
由于 std :: vector
不是线程安全的,我想到了 std :: mutex
这将肯定工作)。
但我想知道我是否可以声明一个向量是原子的,从而绕过互斥体?
是否可能有一个 std :: atomic< std :: vector< int>>
?我可以使用 push_back
等吗?
不需要。从多个线程访问ja std :: vector
是完全可以的,如果
- 您读取对象
- 您写入不同的对象
所以只要确保你创建一个大小为 n = 1000
的向量,并根据你的线程号(1到4),你分配元素0-249,250-499等
因此你的每个线程计算 n / nthreads
元素。 $ b
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 int
s that can be examined by statistics.
Since a std::vector
is not thread-safe, I thought about std::mutex
(which would surely work).
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?
You don't need to. It is totally okay, to access ja std::vector
from multiple threads, if
- you read objects
- you write to different objects
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.
So each of your thread computes n/nthreads
elements.
这篇关于我可以做一个线程安全的std :: atomic< vector< int>>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!