C++多线程基础:std::async异步任务与返回

#include <future>
#include <chrono>
#include <iostream>
#include <cstdlib>

int get_the_answer(int input) {
    std::cout << __FUNCTION__ << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(10000));
    return rand() + input;
}
void do_other_stuff() {
    std::cout << __FUNCTION__ << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}

int main()
{
    // 执行异步任务, 启动策略std::launch::async 即当前直接开启新线程进行处理, get_the_answer直接开始运行
    std::future<int> the_answer = std::async(std::launch::async, get_the_answer, 50);

    // 执行其他操作,异步任务并行处理
    do_other_stuff();
    
    // 这里会先打印 "The answer is " 然后阻塞,等待get_the_answer函数执行完,the_answer得到返回值,get方法才走下去
    std::cout << "wait answer\n" << the_answer.get() << std::endl;

    return 0;
}

 

 

#include <future>
#include <chrono>
#include <iostream>
#include <cstdlib>

int get_the_answer(int input) {
    std::cout << __FUNCTION__ << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(10000));
    return rand() + input;
}

void do_other_stuff() {
    std::cout << __FUNCTION__ << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}

int main()
{
    // 执行异步任务, 启动策略std::launch::deferred, the_answer的get方法调用时get_the_answer线程函数才开始执行
    std::future<int> the_answer = std::async(std::launch::deferred, get_the_answer, 50);

    // 执行其他操作,异步任务并行处理
    do_other_stuff();
    
    // 这里会先打印 "wait answer\n" 然后阻塞,get_the_answer线程函数开始执行,the_answer得到返回值,get方法才走下去
    std::cout << "wait answer\n" << the_answer.get() << std::endl;
    return 0;
}

 

#include <future>
#include <chrono>
#include <iostream>
#include <cstdlib>

int get_the_answer(int input) {
    std::cout << __FUNCTION__ << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(10000));
    return rand() + input;
}
void do_other_stuff() {
    std::cout << __FUNCTION__ << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}

int main()
{
    // 执行异步任务, 自动选择启动策略 std::launch::async 或者 std::launch::deferred ,取决于它们的系统和特定库实现
    std::future<int> the_answer = std::async(get_the_answer, 50);

    // 执行其他操作,异步任务并行处理
    do_other_stuff();

    // 这里会先打印 "The answer is "
    std::cout << "wait answer\n" << the_answer.get() << std::endl;

    return 0;
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页