如何在并行编程中收集从slave返回master的值?

时间:2013-04-17 20:47:39

标签: c++ c multithreading parallel-processing

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

节点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吗?

1 个答案:

答案 0 :(得分:1)

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

  1. std::promise传递给某个主题并设置该值。
  2. 使用std::packaged_task
  3. 致电std::async
  4. 以下是使用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 );