我想使用MPI广播C ++向量。
我不允许使用boost.mpi
现在我使用来自Vector Usage in MPI(C++)的最受欢迎的答案,但它不起作用..
好的,这是代码:
// declaration of variables (ParsedData object will contain these variables)
int generators_count, intervals_count;
std::vector<float> mean_arr, variance_arr, interval_begins_arr, interval_ends_arr;
std::vector<int> amount_of_numbers_to_generate_arr;
// load data into parsed_data object
if (process_id == 0) {
ParsedData parsed_data = load_input_data(filename);
intervals_count = parsed_data.intervals_count;
generators_count = parsed_data.generators_count;
mean_arr = parsed_data.mean_arr;
variance_arr = parsed_data.variance_arr;
interval_begins_arr = parsed_data.interval_begins_arr;
interval_ends_arr = parsed_data.interval_ends_arr;
amount_of_numbers_to_generate_arr = parsed_data.amount_of_numbers_to_generate_arr;
}
// send size of vectors to all processes - that MPI code works
MPI_Bcast(&intervals_count, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&generators_count, 1, MPI_INT, 0, MPI_COMM_WORLD);
// reserve memory for vectors
if (process_id != 0) {
mean_arr.reserve(generators_count);
variance_arr.reserve(generators_count);
amount_of_numbers_to_generate_arr.reserve(generators_count);
interval_begins_arr.reserve(intervals_count);
interval_ends_arr.reserve(intervals_count);
}
// stolen from https://stackoverflow.com/questions/2546298/vector-usage-in-mpic
// broadcast each vector, following code compiles but not works properly
MPI_Bcast(&mean_arr[0], mean_arr.size(), MPI_FLOAT, 0, MPI_COMM_WORLD);
MPI_Bcast(&variance_arr[0], variance_arr.size(), MPI_FLOAT, 0, MPI_COMM_WORLD);
MPI_Bcast(&interval_begins_arr[0], interval_begins_arr.size(), MPI_FLOAT, 0, MPI_COMM_WORLD);
MPI_Bcast(&interval_ends_arr[0], interval_ends_arr.size(), MPI_FLOAT, 0, MPI_COMM_WORLD);
MPI_Bcast(&amount_of_numbers_to_generate_arr[0], amount_of_numbers_to_generate_arr.size(), MPI_FLOAT, 0, MPI_COMM_WORLD);
当我只是简单地将结果放在不同的过程上时,我得到了错误的答案:
cout << "process ID " << process_id << endl << "amount_of_numbers_to_generate_arr[0] " << amount_of_numbers_to_generate_arr[0] << endl;
结果:
using process 0
process ID 0
amount_of_numbers_to_generate_arr[0] 100000000
using process 1
process ID 1
amount_of_numbers_to_generate_arr[0] -423989576
using process 2
process ID 2
amount_of_numbers_to_generate_arr[0] 1741864632
它应该是:
using process 0
process ID 0
amount_of_numbers_to_generate_arr[0] 100000000
using process 1
process ID 1
amount_of_numbers_to_generate_arr[0] 100000000
using process 2
process ID 2
amount_of_numbers_to_generate_arr[0] 100000000
无论如何如何解决这个问题?
或许还有另一种方法可以做到这一点?
答案 0 :(得分:5)
当您“为向量保留内存”时,实际上并没有调整向量的大小。在随后的MPI_Bcast
调用中,向量的大小仍为0
,因此不会收到任何值。
要实际调整向量的大小,请拨打resize
而不是reserve
。