C++ concurrent multithreading --std::async creates asynchronous tasks to create threads

1--std::async creates an asynchronous task

        std::async  creates an asynchronous task , which does not necessarily create a new thread to execute the task;

        When using  std::launch::deferred  , the asynchronous task does not create a new thread ;

        When using std::launch::async , the operating system will force the creation of a new thread to perform asynchronous tasks;

        When std::async creates an asynchronous task without explicitly pointing out the use of std::launch::deferred or std::launch::async, the operating system will randomly adopt a method to execute the asynchronous task (when the system resources are sufficient, A new thread will be created first, otherwise the execution of the asynchronous task will be delayed), you can use  std::future_status  to determine which state the asynchronous task is in ( wait for 0 seconds to judge);

#include <iostream>
#include <thread>
#include <future>

int thread(){
    std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
    return -1;
}

int main(int argc, char *argv[]){
    std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
    // std::future<int> result = std::async(std::launch::deferred, thread); //不会创建一个新线程
    std::future<int> result = std::async(std::launch::async, thread); //强制创建一个新线程
    std::cout << "result.get(): " << result.get() << std::endl;
    return 0;
}

        Use  std::future_status  to determine which state the asynchronous task is in ( wait for 0 seconds to judge);

#include <iostream>
#include <thread>
#include <future>

int thread(){
    std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
    return -1;
}

int main(int argc, char *argv[]){
    std::cout << "thread id: " << std::this_thread::get_id() << std::endl;
    std::future<int> result = std::async(thread);
    std::future_status status = result.wait_for(std::chrono::seconds(0));
    if(status == std::future_status::deferred) { // 异步任务会延迟执行
        std::cout << "deferred running" << std::endl;
        std::cout << "result.get(): " << result.get() << std::endl;
    }
    else{ // 创建新线程来执行异步任务,还需进一步判断是否超时
        std::cout << "create new thread" << std::endl; 
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43863869/article/details/132395907