1、看个例子:
#include <stdarg.h>
#include <thread>
#include <future>
#include <iostream>
#include <unistd.h>
using namespace std;
void test()
{
for (int i = 0; i < 5; ++i)
{
sleep(1);
cout << i << endl;
}
//f.wait();
cout<< "finished test" << endl;
}
int main()
{
std::async(std::launch::async,test);
while (1){
cout << "main thread" << endl;
sleep(1);
}
cout << "end test" << endl;
return 0;
}
运行结果:
0
1
2
3
4
finished test
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
2、修改代码如下:
#include <stdarg.h>
#include <thread>
#include <future>
#include <iostream>
#include <unistd.h>
using namespace std;
void test()
{
for (int i = 0; i < 5; ++i)
{
sleep(1);
cout << i