C++ std::async std::future std::promise

#include <iostream>
#include "common/log.h"
#include <limits>
#include <exception>
#include <future>
#include <unistd.h>
using namespace AdsonLib;
void test_future_promise(){
    // future from a packaged_task
    std::packaged_task<int()> task([]{ return 7; }); // wrap the function
    std::future<int> f1 = task.get_future();  // get a future
    std::thread t(std::move(task)); // launch on a thread
 
    // future from an async()
    std::future<int> f2 = std::async(std::launch::async, []{ return 8; });
 
    // future from a promise
    std::promise<int> p;
    std::future<int> f3 = p.get_future();
    std::thread( [&p]{ p.set_value_at_thread_exit(9); }).detach();
 
    std::cout << "Waiting..." << std::flush;
    f1.wait();
    f2.wait();
    f3.wait();
    std::cout << "Done!\nResults are: "
              << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    t.join();
}
int main(int argc, char *argv[]) {
    LOG(INFO) << "testing...";
    auto fu = std::async(std::launch::deferred, [](){ //std::launch::deferred future.get时运行 std::launch::async异步执行
        LOG(INFO) << "return 123";
        return 123;
    });
    sleep(1);
    LOG(INFO) <<"-------";
    LOG(INFO) << "get: " << fu.get();
    test_future_promise();

}

猜你喜欢

转载自blog.csdn.net/wyg_031113/article/details/128330888