C++20 Coroutines and Thread Safety: implementing std::shared_future
I've been banging my head against this for hours... I am currently working on a C++20 project where I am trying to implement coroutines to handle asynchronous tasks. However, I'm working with unexpected behavior when using `std::shared_future` to get results from multiple coroutines. In particular, when I call `get()` on the shared future from different threads, I sometimes get a `std::future_error` with the message: "No associated state." This usually happens when the coroutine that sets the state is still running. Here is a simplified version of my code: ```cpp #include <iostream> #include <future> #include <thread> #include <coroutine> std::shared_future<int> asyncTask() { co_return 42; } int main() { auto future = asyncTask(); for (int i = 0; i < 5; ++i) { std::thread t([&]() { try { std::cout << "Result: " << future.get() << '\n'; } catch (const std::future_error& e) { std::cerr << "behavior: " << e.what() << '\n'; } }); t.detach(); } std::this_thread::sleep_for(std::chrono::seconds(1)); // Wait for threads to finish } ``` I expected all threads to receive the same result (42) from the future. However, I receive the mentioned behavior sporadically. I also tried using `std::promise` in conjunction with `std::shared_future`, but that led to additional complexity and didn't resolve the scenario. Is there a best practice for sharing results from coroutines safely across multiple threads in C++20? Also, are there any pitfalls I should be aware of regarding thread synchronization in this context? How would you solve this?