繁体   English   中英

cd中的std :: promise和std :: future

[英]std::promise and std::future in c++

std :: promise提供了一种设置值(类型为T)的方法,稍后可以通过关联的std :: future对象读取该值

  1. 这两者究竟如何相关联?

  2. 我的担忧是否合理,未来会与错误的承诺结合?

更新:来自行动中的并发的示例...(但代码无法编译)

#include <future>
void process_connections(connection_set& connections)
{
    while(!done(connections)){
        for(connection_iterator
        connection=connections.begin(),end=connections.end();
        connection!=end;
        ++connection)
        {
            if(connection->has_incoming_data()){
                data_packet data=connection->incoming();
                std::promise<payload_type>& p=
                connection->get_promise(data.id);
                p.set_value(data.payload);
            }
            if(connection->has_outgoing_data()){
                outgoing_packet data=
                connection->top_of_outgoing_queue();
                connection->send(data.payload);
                data.promise.set_value(true);
            }
        }
    }
}
  1. promisefuture想象成为数据创建一次性使用渠道。 promise创建通道,并最终使用promise::set_value将数据写入其中。 future连接到channel, future::wait读取并返回数据。

  2. 没有真正关心,因为将futurepromise “配对”的唯一方法是使用promise::get_future

  1. 它们由std::promise::get_future成员函数关联。 通过调用此函数,您可以获得与std::promise关联的std::future

    std::future表示您尚未拥有但最终会拥有的值。 它提供了检查值是否可用的功能,或等待它可用的功能。

    std::promise承诺最终会设置一个值。 当最终设置一个值时,它将通过其相应的std::future

  2. 不,因为您在创建后不会将它们配对。 你从std::promise得到你的std::future ,所以它们本身就是联系在一起的。

std::promise<class T> promiseObj;

  1. promise对象创建一个可以存储T类型值的容器

std::future<class T> futureObj = promiseObj.get_future();

  1. 未来对象一旦保存了某个值,就会检索promise对象创建的容器中的内容。 未来的对象需要与promise对象创建的容器相关联,这可以通过上面的代码片段完成。 因此,如果您将未来与预期的promise对象关联起来,那么未来不应该与错误的promise对象配对。

  2. 这是一个示例程序,可以明确未来承诺的使用:

     #include <iostream> #include <thread> #include <future> //Some Class will complex functions that you want to do in parallel running thread class MyClass { public: static void add(int a, int b, std::promise<int> * promObj) { //Some complex calculations int c = a + b; //Set int c in container provided by promise promObj->set_value(c); } }; int main() { MyClass myclass; //Promise provides a container std::promise<int> promiseObj; //By future we can access the values in container created by promise std::future<int> futureObj = promiseObj.get_future(); //Init thread with function parameter of called function and pass promise object std::thread th(myclass.add, 7, 8, &promiseObj); //Detach thread th.detach(); //Get values from future object std::cout<<futureObj.get()<<std::endl; return 0; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM