fork() vs std::async in C++

Viewed 595

I am new to concepts of asyc and fork, what I understood till now is that the fork() creates chid processes which will run asynchronously. And the std::async will create a thread from the system pool and launch it asynchronously here if I mention std::launch::async.

For instance how does below set of code differs? 1: using std::async

std::vector<std::future<void>> result;
for(i=0;i<5;i++){
    result. push_back(std::async(std::launch::asyc, foo, var1));
}

for( auto e : result) 
    e.get();

2nd: Using fork()

for(i=0;i<5;i++){ 
    if(fork()==0){
        foo(var1);
        exit(0);
    }
}

Assume the foo function return type is void, and the arguments are passed as reference or pointers.

2 Answers

The key difference is that in the case of std::async, the two threads of execution share a process. In the case of fork, they each have their own process.

This difference most significantly affects things that change after the call. In the case of fork, each process can then open and close its own file descriptors, manage its own memory space, and so on. In the case of std::async, the threads continue to share file descriptors, memory space, and so on.

fork()

fork() creates a child process by duplicating the calling process. The child process is detached from the parent process so each has its own memory and without setting up any inter-process communication channels it is impossible to pass data between the two processes. The most common use case for calling fork() is to start a process as a background service (a.k.a. "daemon"). For example when you start your favorite web server on the command line, it might fork off a child process (the actual server process). Once that's done the main process ends so control returns back to your shell and you can do other things.

std::async

std::async executes a function in a separate thread (assuming policy std::launch::async). It returns a std::future on which you can call get() to get the value returned by the function (assuming it returned and didn't throw an exception). The get() call returns immediately if the function has completed in the meantime, otherwise it blocks until the function has returned. This feature makes std::async a useful tool for running expensive computations in the background while doing something else.

Related