不同的编译器/标准库实现可能会有不同的默认策略。例如,Visual C++默认使用多线程一次性策略,而GCC默认使用惰性策略。在C++17中,std::launch::async和std::launch::deferred作为可选标志之一可以传递给std::async,以强制选择特定策略。
以下代码示例说明了默认std::async策略如何解析,并使用launch::async标志来指定特定策略:
#include
#include
using namespace std;
int MyFunction() {
cout << "MyFunction is called." << endl;
return 0;
}
int main() {
auto future = std::async(std::launch::async, MyFunction); //强制使用async策略
future.wait();
auto future2 = std::async(std::launch::deferred, MyFunction); //强制使用deferred策略
future2.wait();
auto future3 = std::async(MyFunction); //使用默认策略
future3.wait();
return 0;
}
在上面的代码中,我们可以使用std::launch::async和std::launch::deferred显式地指定策略。最后,我们使用没有指定标志的std::async来使用默认策略。