问题描述
我有一个函数需要执行 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 int
s 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>> 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!