范例一:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
void aa()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
while (1) {
}
}
void run()
{
auto it = std::async(aa);
}
int main()
{
{
auto it = std::async(aa);
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
}
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
return 0;
}
范例二:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
return 3;
}
int main()
{
auto it = std::async(run);
std::cout << it.get() << std::endl;
return 0;
}
范例三:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
return 3;
}
int main()
{
auto it = std::async(run);
it.wait();
return 0;
}
范例四:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
return 3;
}
int main()
{
auto it = std::async(std::launch::deferred,run);
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
it.wait();
return 0;
}
std::async的参数还有其它,大家可以自行尝试。
|