C++ Concurrency High-Level Interface: std::async and std::future

std::async和std::future

std::asyncCreate a background thread to execute the passed task, as long as this task is a callable object, and then return one std::future. The future stores a state shared by multiple threads, and when future.get is called, it will block until the bound task is executed:

#include <iostream>
#include <future>

void task() {
    for (int i = 0; i < 10; i++) {
        std::cout << "A";
    }
}

int main() {
    std::future<void> result{ std::async(task) };
    for (int i = 0; i < 10; i++) {
        std::cout << "B";
    }
    result.get();   //强制阻塞main线程,直到task线程执行完毕
    system("pause");
    return 0;
}

std::launch::async

The above task returns void, this result is useless, we just want to wait for the end of the task thread.
There is also a simpler method for this requirement: specify a launch policy

#include <iostream>
#include <future>

void task() {
    for (int i = 0; i < 10; i++) {
        std::cout << "A";
    }
}

int main() {
    std::future<void> result{ std::async(std::launch::async,task) };
    for (int i = 0; i < 10; i++) {
        std::cout << "B";
    }
    system("pause");
    return 0;
}

Specify a launch policy when creating async, even result.get can be used, but you still need to assign the return value of async to result. If you do not assign async, it will block here like a synchronous call until the call is completed, which is equivalent to useless async.

There are two launch policies in total:

  • std::launch::asyncWhen the returned future is invalid, the task will be forced to execute, that is, the execution of the task will be guaranteed without calling future.get
  • std::launch::deferredThe task will only be executed when future.get is called.
    If the launch policy is not specified when creating async, it will default std::launch::async|std::launch::deferredto one and choose one to execute according to the situation.

std::launch::deferred

Try the std::launch::deferredstrategy again.

#include <iostream>
#include <future>

void task() {
    for (int i = 0; i < 10; i++) {
        std::cout << "A";
    }
}

int main() {
    std::future<void> result{ std::async(std::launch::deferred,task) };
    for (int i = 0; i < 10; i++) {
        std::cout << "B";
    }
    result.get();
    system("pause");
    return 0;
}

The program outputs BBBBBBBBBBAAAAAAAAAA , as we said, when async is created, it does not start a new thread to execute the task, but waits until result.get is executed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325118280&siteId=291194637