等待结果按顺序循环

时间:2020-04-05 20:14:55

标签: c++ multithreading asynchronous std

尝试并行化计算方法,然后等待从所有计算中收集结果,并将其与其他数据注入一起存储在std :: list中,因此看不到性能提高。也许如果我知道'num_results',那么我可以合并两个循环并将数据仅通过锁定(mutex)写(push_back)过程存储在列表中吗?另一件事是如何保留顺序(如果某些[i]计算速度很快) 在一个内核中的一个周期内执行此操作太慢。

// here is pseudocode 

void SomeClass::SomeMethod() {
  size_t num_results = request_list.size();
  std::list<result_t> some_results;
  float *result = new float[num_results];
  // linearly I do one for in where one parameter of list pushing are long computing function
  // so I create array of function results and try to store data same time then wait and collect in list with other data
  for (size_t i(0); i < num_results; i++) {
     // Calculate is hard function and may vary in times depending on imput
     // use temporary thread object and labda function to acces class members data
     thread t([&]() { result[i] = Calculate(request_list[i]); });
     // where or how to wait for all results stored in array only then push them to list?

     t.join(); // where or how to wait for all result[] for next cycle or merge both? 
  } 
  // conjugate result with some other data from static list with same id's
  for (std::size_t i(0); i < num_requests; i++) {
      some_results.push_back( result_t(result[i], other_data[i], ...) );
  }

  delete [] result; // free memory

   // Continue job with some_results list

}

我在做平行论错误吗?

2 个答案:

答案 0 :(得分:0)

再次查看join函数,您将启动一个计算线程,等待该线程,然后再启动另一个线程。相反,您应该启动多个线程,然后再加入它们。您的操作顺序是错误的,因为您等待每个线程。

http://www.cplusplus.com/reference/thread/thread/join/

答案 1 :(得分:0)

// solution for dynamic async threads with store results 
// after lots of documentation reading of multithreading
// function do asynchronic calls of N count of heavy ops then waits in idle 
// cycle to aquire all results, if first is ready push it to vector
// while it waits for first result accesible, next maybe ready allready    


void SomeClass::SomeMethod() {
   auto request_util = [&](std::size_t i) { return Calculate(i); };
   size_t num_results = request_list.size();
   std::list<std::future<float>> request_respond_list;
   for (std::size_t i(0); i < num_requests; i++)
      request_respond_list.push_back( std::async(std::launch::async, request_util, i));

   std::size_t id(0);

   // example of result storing
   // float *result = new float[num_results];
   std::vector< result_t > results;
   while (!request_respond_list.empty()) {
      if (request_respond_list.front().valid()) {
          results.push_back(result_t(request_respond_list.front().get(), other_data[id]));
          request_respond_list.pop_front();
          id++;
      } else
         std::this_thread::yield();
   } request_respond_list.clear();

  // do other job with results vector
   ....
}