如何在并行编程中收集从机到主机返回的值



我正试图找到一种正确的方法来收集并行编程中从机返回到主机的值。我之前也问过类似的问题,关于如何划分工作来计算mandelbrot的像素。我得到了如何发送作品的答案,但仍在努力收集数据并将其绘制为像素。

节点0:(主(

节点1:(从(

v[0]  = {2,3,4,5,67,86,56,5} // core 0 holds value of 8 threads of this core
v[1]  = {12,21,4,3,54,65,6,5,4} // core 1 holds value of 9 threads of this core
v[2]  = {1,3,4,54,6,5,65,7,4}  //core 2 holds value of 9 threads of this core

节点2:(从(

v[0]  = {2,3,4,5,67,86,56,5} // core 0
v[1]  = {12,21,4,3,54,65,6,5,4} // core 1 
v[2]  = {1,3,4,54,6,5,65,7,4}  //core 2

节点3:(从(

v[0]  = {2,3,4,5,67,86,56,5} // core 0
v[1]  = {12,21,4,3,54,65,6,5,4} // core 1 
v[2]  = {1,3,4,54,6,5,65,7,4}  //core 2

因此,当master想要这些值时,slave应该附加向量并发送,或者有其他更好的方法将值传递给master吗?

如果您使用的是C++11线程库(或Boost.thread(,那么您可能想要的是std::future。它们可以通过以下三种方式之一获得:

  1. 通过将std::promise传递给线程并让它设置值
  2. 通过使用CCD_ 3
  3. 通过调用std::async

以下是使用std::async:的示例

some_return_type my_work_function( some_input_type const & );
some_input_type inputs_to_slave_threads[] = { /* ... */ };
std::future< some_return_type >
  // launch the slaves, letting the OS decide whether to spawn new threads
  slave_0_future = std::async( my_work_function, std::ref( inputs_to_slave_threads[0] ) ),
  slave_1_future = std::async( my_work_function, std::ref( inputs_to_slave_threads[1] ) ),
  // ...
  slave_N_future = std::async( my_work_function, std::ref( inputs_to_slave_threads[N] ) );
some_return_type
  // block until results are ready
  result_of_slave_0 = slave_0_future.get(),
  result_of_slave_1 = slave_1_future.get(),
  // ...
  result_of_slave_N = slave_N_future.get();
process_results_of_slaves( result_of_slave_0, ..., result_of_slave_N );

最新更新