multithreading - Is it possible to multithread to execute non-void functions at the same time? (C++) -


suppose have function log transforms vector, multiplied constant, defines function maps, given vector, , constant....

vector<double> logtransform(vector<double> &data, int constant){     vector<double> image;     (int = 0; < data.size(); i++){         image.push_back(constant*log(data[i]));     }     return image; } 

given vector named "data", need apply function "logtransform" varying number of constants, contained in array of doubles, how can use multithreading execute function @ same time if function not void type?

you can use std::future collect results other threads when ready this:

std::vector<double> logtransform(std::vector<double> const& data, int constant) {     std::vector<double> image;     image.reserve(data.size());      std::transform(std::begin(data), std::end(data), std::back_inserter(image),         [constant](double d){ return constant * std::log(d); });      return image; }  int main() {     std::vector<double> data = {0.3, 0.7, 0.9};      // start thread transform     // remember pass data reference using std::cref() (constant reference)     auto future = std::async(std::launch::async, logtransform, std::cref(data), 5);      // else in parallel     for(auto = 0; < 10; ++i)         std::cout << " " << i;     std::cout << '\n';      // collect results     auto results = future.get(); // wait if thread not finished      for(auto d: results)         std::cout << " " << d;     std::cout << '\n'; } 

note: requires c++11

the function std::async launches thread work , returns std::future can use pick results later.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -