传入线程函数
eg:
#include <iostream>
#include <string.h>
#include <thread>
#include <future>
using namespace std;
int func(int user_data)
{
cout << "child thread start, id is " << std::this_thread::get_id() << endl;
for(int i = 0; i < 10; ++i)
{
cout << "i = " << i << endl;
std::this_thread::sleep_for(1s);
}
cout << "child thread exit, id is " << std::this_thread::get_id() << endl;
return user_data + 1;
}
int main()
{
cout << "main thread start, id is " << std::this_thread::get_id() << endl;
future<int> ft = async(std::launch::async, func, 998);
for(int j = 0; j < 5; ++j)
{
cout << "j = " << j << endl;
std::this_thread::sleep_for(1s);
}
cout << "main thread end, id is " << std::this_thread::get_id() << endl;
cout << "child thread return is " << ft.get() << endl; // 会一直阻塞到子线程返回
system("pause");
return 0;
}
结果如下所示: