std::cout << std::thread::hardware_concurrency() << std::endl;
///////////////////////////////////////////////////////////////////////////////////////////////////
std::future_status status = std::future_status::ready;
std::future<int> result1 = std::async(std::launch::async, [](void*p)->int {
for (auto i = 0; i < 100; i++)
{
std::cout << std::this_thread::get_id() << ", value=" << i << std::endl;
}
return 0;
}, nullptr);
do {
//enum type future status
status = result1.wait_for(std::chrono::microseconds(0));//sleep 0 micro seconds
switch (status)
{
case std::future_status::ready:
{
//task execute success and return ready
std::cout << "task thread execute success and return ready." << std::endl;
std::cout << result1.get() << std::endl;
}
break;
case std::future_status::timeout:
{
//timeout: task thread is running.sleep 0 micro seconds,return ready;if not,return timeout
std::cout << "timeout: task thread is running." << std::endl;
}
break;
case std::future_status::deferred:
{
//task thread delay running, system resource tight
std::cout << result1.get() << std::endl;
}
break;
default:
{
}
break;
}
} while (status != std::future_status::ready);
///////////////////////////////////////////////////////////////////////////////////////////////////
std::promise<int> prom; // 生成一个 std::promise<int> 对象.
std::future<int> fut = prom.get_future(); // 和 future 关联.
std::thread t([](std::future<int>& fut) {
int x = fut.get(); // 获取共享状态的值.
std::cout << "value: " << x << '\n'; // 打印 value: 10.
}, std::ref(fut)); // 将 future 交给另外一个线程t.
prom.set_value(10); // 设置共享状态的值, 此处和线程t保持同步.
t.join();
///////////////////////////////////////////////////////////////////////////////////////////////////
std::packaged_task<int(int)> my_task([](int x) { for (auto i = 0; i < 1000000; i++)
{
std::cout << std::this_thread::get_id() << ", value=" << i << std::endl;
}return x * 3; }); // package task
std::future<int> my_future = my_task.get_future(); // 获取 future 对象.
std::thread(std::move(my_task), 100).detach(); // 生成新线程并调用packaged_task.
int value = my_future.get(); // 等待任务完成, 并获取结果.
std::cout << "Thre triple of 200 is " << value << ".\n";
///////////////////////////////////////////////////////////////////////////////////////////////////
return 0;