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
- I get that
std::promisebecomes satisfied whenset_valueis called. But how do I assign a value in advance and then makestd::futurereact to it being changed (for instancefuturewould react tofalseboolbeing changed totrue)? - Would I ever need to do such a thing?
- Does
std::promisehas default values for certain types (if it needs such at all)?
std::promise"Note that thestd::promiseobject is meant to be used only once."atomic_thread_fencein this example, thepromisealready takes care of memory ordering (that is also explained in documentation).