Search
 
SCRIPT & CODE EXAMPLE
 

CPP

std::future

#include <iostream>
#include <future>
#include <thread>
 
int main()
{
    // 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!
Results are: "
              << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '
';
    t.join();
}
Comment

std::future

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

int main() {
    // 将一个返回值为7的 lambda 表达式封装到 task 中
    // std::packaged_task 的模板参数为要封装函数的类型
    std::packaged_task<int()> task([](){return 7;});
    // 获得 task 的期物
    std::future<int> result = task.get_future(); // 在一个线程中执行 task
    std::thread(std::move(task)).detach();
    std::cout << "waiting...";
    result.wait(); // 在此设置屏障,阻塞到期物的完成
    // 输出执行结果
    std::cout << "done!" << std:: endl << "future result is " << result.get() << std::endl;
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: inline function in cpp 
Cpp :: c++ insert hashmap 
Cpp :: move assignment operator c++ 
Cpp :: cyclically rotate an array by once 
Cpp :: tabeau pseudo dynamique sur c++ 
Cpp :: how to print an array in cpp in single line 
Cpp :: c++ - 
Cpp :: size of unordered_set 
Cpp :: what is the time complexitry of std::sort 
Cpp :: web dev c++ 
Cpp :: hello world programming 
Cpp :: c++ string concatenation 
Cpp :: copy vector c++ 
Cpp :: memcpy in cpp 
Cpp :: Array Rotate in c++ 
Cpp :: long long vs long long int 
Cpp :: quicksort algorithm 
Cpp :: remove duplicates from sorted list solution in c++ 
Cpp :: ifstream file (“code2.txt”); dev C++ 
Cpp :: using-controller-and-qt-worker-in-a-working-gui-example 
Cpp :: css window id 
Cpp :: Vaccine Dates codechef solution in c++ 
Cpp :: c++ error missing terminating character 
Cpp :: prompt user for bool statement C++ 
Cpp :: increment integer 
Cpp :: Get the absolute path of a boost filePath as a string 
Cpp :: ternary operator rsut 
Cpp :: the question for me 
Cpp :: loops in c++ with example 
Cpp :: c/c++ pointers 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =