lundi 5 avril 2021

Need help understanding how std::promise and std::future work in this case

Code

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

void listenForInput(std::promise<bool>&& interruptPromise)
{
    std::cin.get();
    std::atomic_thread_fence(std::memory_order_acquire);
    interruptPromise.set_value(true);
    std::cout << "[Speech 100] no u \n";
}

bool is_ready(std::future<bool> const& f)
{ 
    return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready; 
}

int main() 
{
    std::atomic_thread_fence(std::memory_order_acquire);
    std::promise<bool> interruptPromise;
    //interuptPromise.set_value(false); 
    /* Commenting line above makes program work. Uncommenting results in while
       loop below not being executed */
    std::atomic_thread_fence(std::memory_order_release);
    
    std::future<bool> interruptFuture = interuptPromise.get_future();
    
    std::thread reply(listenForInput, std::move(interruptPromise));
    
    while (!is_ready(interruptFuture))
    {
        std::cout << "Your mother was a hamster, "
                     "and your father smelt of elderberries "
                     "(Press any key to reply)\n";
        std::this_thread::sleep_for( std::chrono::seconds(2) );
    }
    
    reply.join();
    
    std::cin.get();
    
    return 0;
}

Context

In the code above in the main thread the same line of text is constantly being displayed until it's interrupted from the other thread. The interrupt occurs after any input from the user. The message of user making an input is being delivered to the main thread via std::promise and std::future. is_ready is an utilitarian function used for checking whether promise was satisfied.

My interest lays in the third line of the main() function and what's around it. At first I tried to set value of interruptPromise in advance to false (which would indicate that interrupt didn't occur so that later in other thread I'd change it to true to indicate that it did occur). It resulted in interruptPromise being satisfied before while loop even started thus the loop not being executed.

Questions

  1. I get that std::promise becomes satisfied when set_value is called. But how do I assign a value in advance and then make std::future react to it being changed (for instance future would react to false bool being changed to true)?
  2. Would I ever need to do such a thing?
  3. Does std::promise has default values for certain types (if it needs such at all)?

Aucun commentaire:

Enregistrer un commentaire