Search code examples
c++cmultithreadingfork

call a function many times in parallel


I want to call a function with different value of arg many times. To make the execution faster I want to call the function without considering its implementation.

Inside a loop i pass the arg to the function and call it now my program should not wait for the function to execute and loop again, instead it should not consider that the function has not completed for the first loop it should go ahead and call the function again and again till the loop ends.

how to use fork and threads to do this , which one will be faster and a skeleton of code will help ? Lets say my function is void foo(arg1,arg2)


Solution

  • You want an asynchronous implementation of the proactor pattern.

    Here's an example, using boost::asio and boost::thread:

    #include <iostream>
    using namespace std;
    
    #include <boost/asio.hpp>
    #include <boost/thread.hpp>
    
    // your function, with its arguments
    void foo(int x, int y)
    {
       cout << x << " * " << y << " = " << x * y << "\n";
    }
    
    int main()
    {
       boost::asio::io_service svc;
       boost::asio::io_service::work w(svc);
    
       // create a thread to run the io_service proactor
       boost::thread thread(boost::bind(&boost::asio::io_service::run, &svc));
    
       for(int z = 0; z < 32; ++z)
       {
          // bind the function to its arguments to 
          // be called in the context of the running
          // thread
          svc.post(boost::bind(&f, 2, z));
       }
    
       boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
    
       svc.stop();
       thread.join();
    }
    

    The benefit here, is you can scale easily by calling boost::asio::io_service::run from a pool of threads if necessary.