Std :: prom and std :: future in C ++

std :: prom provides a means of setting a value (of type T), which can later be read through the associated std :: future object

  • How exactly are these two connected?

  • Is my concern reasonable that the future will be fraught with a wrong promise?

update: example from concurrency in action ... (code cannot compile, though)

#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);
            }
        }
    }
}
+5
source share
3 answers
  • Think of promiseand futurehow to create a one-time feed for data. promisecreates a channel and, in the end, writes data with promise::set_value. futureIt connects to the channel, and future::waitreads and returns data after they are written.

  • , "" a future promise promise::get_future.

+4
  • std::promise::get_future. std::future, std::promise, .

    A std::future , , . , , , .

    A std::promise , . , std::future.

  • , . std::future std::promise, .

+2

std::promise<class T> promiseObj;

  1. , T

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

  1. , , , . , , . , , , .

  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;
    }
    
0

All Articles