CPP Advanced multi-threading Flashcards
1
Q
Futures
A
Class introduced in C++11 to access values set by specific providers.
Providers set the shared state to ready when the value is set.
2
Q
Future
A
- A future is an object that can retrieve a value from some provider object or function, handlying syncrhonization properly if in different threads.
- future future_name;
- future::get() can be called only once on a future.
- future has move semantics, no copy semantics.
- Shared futures also exist:
- behaves like a future, but it can be shared
- ownership can be shared
- value that it holds can be retrieved more than one time
3
Q
Promise
A
- Is an object that can store a values that can be retrived by a future object (even if in another thread).
- On contruction promise objects are associated with a shared state where they can store the value of type t
- The state can be associated with a future calling get_future
- After the call, promise and the future associated share the same state:
- Promise: is an async. provider, expected to set the value
- can store also an exception: set_exception instead of set_value
- exceptions are fired on calling .get on the future
- Future: async. return object that can retrieve the value of the shared state waiting for it to be ready.
- Promise: is an async. provider, expected to set the value
4
Q
Future providers: async
A
- An higher level way of using futures without std::threads is made possible by async
- with 3 different types of policies:
- launch::async: launch a new async thread to call function
- launch:deferred: the call to the function will be executed upon calling wait or get on the future
- async | deferred: let the system choose the strategy based on current resource availability.
- with 3 different types of policies:
5
Q
Thread communication with futures
A
- Pass the promise to a function to let it set the value
- Pass the future associated with the promise to the other function
- * Remember to move() them, they can’t be copied
6
Q
Future Providers: packaged_task
A
- Wraps around a normal function with a non-future return value
- Returns a future that can be waited upon to get the return value
- We could move also the task into a std::thread
7
Q
Task based vs Thread based programs
A
- Task:
- Functions return value is accessible
- Smart task/thread spawning with default policy
- Exception handling through futures
- Thread:
- Usually don’t terminate until the end of the program
- More general concurrency model, can be used to design any mulitprogramming pattern
- Access to lower level options (pthread native handle)
- priority, affinity, scheduling policies