我正在用C ++写一个蒙特卡洛程序,并且正在使用std :: thread划分线程之间要跟踪的历史记录数量。但是,这是我第一次尝试多线程,并且遇到了一个问题,希望该简化的代码可以让我进行演示,以期能从本站点的读者那里获得一些建议。在这个简化的问题中,我将调用求和函数,该函数将生成具有2个线程的1X5维随机数数组。当线程返回它们的值时(由于它是一个全局变量而没有真正返回),则主程序将具有两个5维数组,每个数组对应于一个不同的线程。我想将两个数组合并成一个数组,最后一个数组中的元素,对应于由不同线程产生的两个数组中相同元素的总和。不幸的是,每个线程中的数组具有相同的名称,因此我不能简单地将两个不同的数组加在一起。建议使用哪些方法将两个1X5维数组组合为一个单个求和数组,并使用与每个线程中相同元素之和相对应的元素?
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <cassert>
#include "boost/multi_array.hpp"
std::vector<float> Array;
std::mutex Array_mutex;
void Summation(int sample_size)
{
std::lock_guard<std::mutex> guard(Array_mutex);
for(int i = 0; i < sample_size; i++)
{
Array.push_back(rand() % 10 + 1);
}
std::cout << "\n";
}
int main(int argc, const char * argv[]) {
int sample_size = 10;
int Num_Threads = 2;
int number_count = sample_size/Num_Threads;
srand(time(NULL));
std::vector<std::thread> Threads;
for(int i = 0; i < Num_Threads; i++)
{
Threads.push_back(std::thread(Summation,number_count));
}
for(int i = 0; i < Num_Threads; i++)
{
Threads[i].join();
}
// - I would like to combine the arrays produced from each thread into a
// single array, where each element in the final array is the sum of
// the identical element in the array from each thread
// i.e. Element 1(final) = Element 1(thread 1) + Element 1(thread2)
// Element 2(final) = Element 2(thread 1) + Element 2(thread2)
// Element 3(final) = Element 3(thread 1) + Element 3(thread2)
return 0;
}
如果每个线程需要一个向量,则实际上每个线程需要一个向量。就像向量的向量。
对于一个简单而幼稚的解决方案,类似
#include <iostream>
#include <array>
#include <random>
#include <thread>
void generate(const size_t size, std::array<float>& values)
{
// Pseudo-random number generation stuff
std::random_device rd;
std::default_random_engine e1(rd());
std::uniform_int_distribution<float> uniform_dist(1, 10);
// Generate some values and add the array
for (size_t i = 0; i < size; ++i)
values[i] = uniform_dist(el);
}
int main()
{
constexpr size_t number_values = 10;
constexpr size_t number_threads = 2;
// An array of arrays, one sub-array per thread
std::array<std::array<float, number_values>, number_threads>
values;
// An array of threads
std::array<std::thread, number_threads> threads;
// Create threads
for (size_t i = 0; i < number_threads; ++i)
threads[i] = std::thread(generate, number_values, std::ref(values[i]));
// Wait for threads to finish
for (size_t i = 0; i < number_threads; ++i)
threads[i].join();
// Now "combine" the values into a single array
std::array<float, number_values> totals;
for (size_t i = 0; i < number_values; ++i)
{
for (size_t j = 0; j < number_threads; ++j)
totals[i] += values[j][i];
}
// Print the values
for (const size_t i; i < number_values; ++i)
std::cout << "Value #" << (i + 1) << " = " << totals[i] << '\n';
}
请注意,该代码未经测试,甚至没有经过编译,但应在理论上起作用。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句