我正在学习如何使用线程,我无法理解为什么使用future会使程序按预期异步运行,但是当我不使用它时,async
似乎是阻塞的。为什么这两个程序都不需要3秒钟才能运行?我不明白为什么案例1需要6秒钟?
案例1:较慢的版本
观察:阻止?我没想到这需要6秒才能运行。我认为调用异步会产生一个单独的执行线程。但相反,似乎函数sendmsg()
需要3秒然后完成,然后getmsg()
需要额外的3秒。我没有看到在这里同时执行2个线程的证据。
$ 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);
}
案例2:更快的版本
观察:在这种情况下,程序只需3秒即可运行!唯一的区别是我正在使用未来。
$ 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
}