thread,packaged_task,promise

Thread,Packaged_task,Promise 运用

#include 
#include 
#include 
#include 
#include 


int func(std::future<int> &fut)
{
    int val = fut.get();
    std::cout<<"thread "<<std::this_thread::get_id()<<" is going to sleep for "<<val<<" seconds..."<<std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(val));
    return val;
}

int main()
{
    std::packaged_task<int(std::future<int> &)> packtask(std::ref(func));
    std::promise<int> ap;
    std::future<int> fut = ap.get_future();
    std::thread th(std::move(packtask),std::ref(fut));
    std::cout<<"thread "<<std::this_thread::get_id()<<" is going to sleep for "<<5<<" seconds..."<<std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(5));
    ap.set_value(3);
    if(th.joinable())
    {
        th.join();
    }

}

你可能感兴趣的:(thread,packaged_task,promise)