CodexBloom - Programming Q&A Platform

advanced patterns when using std::promise and std::future in C++17 with multiple threads

πŸ‘€ Views: 81 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-18
c++ multithreading promise future cpp

Does anyone know how to I tried several approaches but none seem to work... I'm having trouble with `std::promise` and `std::future` in my C++17 application. My intention was to signal completion of work from multiple threads, but I'm working with unexpected behavior. Specifically, it seems that once the promise is set, subsequent calls to `set_value` are causing a `std::future_error` with the message `future already satisfied`. I've implemented a simple example where I create multiple threads that are supposed to set the value of the same promise. Here’s the relevant code snippet: ```cpp #include <iostream> #include <thread> #include <future> #include <vector> void worker(std::promise<int>& promise) { // Simulating some work std::this_thread::sleep_for(std::chrono::milliseconds(100)); promise.set_value(42); } int main() { std::promise<int> promise; std::future<int> future = promise.get_future(); std::vector<std::thread> threads; for (int i = 0; i < 3; ++i) { threads.emplace_back(worker, std::ref(promise)); } for (auto& t : threads) { t.join(); } std::cout << "Value from future: " << future.get() << std::endl; return 0; } ``` I expected to see `Value from future: 42`, but instead, I get the behavior about the future already being satisfied after one thread successfully sets the value. It seems like only one thread is allowed to set the promise, but I was under the impression that I could have multiple threads trying to do so and the first one to succeed would set the value. What am I doing wrong? Should I be using a different synchronization primitive for this use case? Any insights on how to handle the situation properly would be greatly appreciated! What am I doing wrong? This is happening in both development and production on Debian. Any advice would be much appreciated.