mardi 30 décembre 2014

Why does async seem to be blocking? [duplicate]


This question already has an answer here:




I am learning how to use threading and I am having trouble understanding why the use of future makes the program run asynchronously as expected, but when I do not use it, async seems to be blocking. Why don't both of these programs take 3 seconds to run? I don't understand why Case 1 takes 6 seconds?


CASE 1: slower version


Observation: Blocking? I didn't expect this to take 6 seconds to run. I thought that calling async would spawn a separate thread of execution. But instead, it seems the function sendmsg() takes 3 seconds and then completes, and then getmsg() takes the additional 3 seconds. I don't see evidence of 2 threads being executed simultaneously here.



$ time ./filesync

real 0m6.018s
user 0m0.001s
sys 0m0.003s

$ cat main.cpp
#include <iostream>
#include <stdlib.h>
#include <future>
#include <unistd.h>

int sendmsg()
{
sleep(3);
return 5;
}

int getmsg()
{
sleep(3);
return 10;
}

int main(int argc, char** argv)
{
std::async(std::launch::async, sendmsg);
std::async(std::launch::async, getmsg);
}


CASE 2: faster version


Observation: In this case, the program only takes 3 seconds to run total! The only difference is that I am using future.



$ time ./filesync

real 0m3.017s
user 0m0.002s
sys 0m0.003s

$ cat main.cpp
#include <iostream>
#include <stdlib.h>
#include <future>
#include <unistd.h>

int sendmsg()
{
sleep(3);
return 5;
}

int getmsg()
{
sleep(3);
return 10;
}

int main(int argc, char** argv)
{
std::future<int> f1 = std::async(std::launch::async, sendmsg);
std::future<int> f2 = std::async(std::launch::async, getmsg);
int finalval = f1.get() + f2.get(); // even when I comment this line out,
// it still only takes 3 seconds to run
}

Aucun commentaire:

Enregistrer un commentaire