0

Is promise future needed ?

We don't have callable function passed to thread returns value. So, Std::ref is the one which helps Other option is using promise which also help to provide us value out of thread function I have used both the approach in below code. Question 1 : So, Why so much complication of promise and future when we can use std::ref easily Question 2 : Is there any other use case of future and promise or is it just unnecessary alternate? Question 3 : Also, future promise is complication as we have to join thread also which is blocking call and future.get is also a blocking call. https://sololearn.com/compiler-playground/cBMoWNzA2Fph/?ref=app

8th Mar 2025, 7:52 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Antwort
0
1. Why use std::promise and std::future over std::ref? While std::ref can work when you just want to modify a shared variable, it's not thread-safe by default. std::promise and std::future provide a synchronized, safer way to pass results from threads, especially when you don't want to deal with locks. 2. Use cases where promise/future are better: When the data will be available asynchronously at a later point. When you want synchronization between threads (e.g., a producer-consumer pattern). To avoid race conditions in multi-threaded environments. For complex threading workflows like std::async, task chaining, etc. 3. Blocking concern: Yes, future.get() is a blocking call, but that’s often what we need—it waits until the thread has finished its job and produced the result. If you don’t want to block, you can use wait_for() or wait_until() to check status. So, while std::ref works in simpler cases, promise/future give you greater control and safety in complex or asynchronous systems.
6th Apr 2025, 6:45 PM
Meenakshi Guntuku
Meenakshi Guntuku - avatar