C/C++ 異步調用

#include <future>
#include <iostream>
#include <string>

std::string helloFunction(const std::string& s) {
    return "Hello C++11 from " + s + ".";
}

class HelloFunctionObject {
public:
    std::string operator()(const std::string& s) const {
        return "Hello C++11 from " + s + ".";
    }
};

int main() {
    std::cout << std::endl;
    // 帶函數的future
    auto futureFunction = std::async(helloFunction, "function");
    // 帶函數對象的future
    HelloFunctionObject helloFunctionObject;
    auto futureFunctionObject = std::async(helloFunctionObject, "function object");
    // 帶匿名函數的future
    auto futureLambda = std::async([](const std::string& s) {return "Hello C++11 from " + s + "."; }, "lambda function");
    std::cout << futureFunction.get() << "\n"
              << futureFunctionObject.get() << "\n"
              << futureLambda.get() << std::endl;
    std::cout << std::endl;
}

g++ main.cpp -std=c++11 -lpthread

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章