Multithreading Quiz - Languages C++
Free practice quiz: Multithreading (Languages C++). 51 multiple-choice questions with answers and explanations. Play online, no sign-up needed.
Play all 51 questions freeSample questions
Which C++ standard library header provides classes and functions for multithreading support?
- <thread>
- <mutex>
- <condition_variable>
- <future>
Show answer
Answer: A. <thread>
The `<thread>` header in C++11 and later provides the `std::thread` class, which is the fundamental building block for creating and managing threads.
What is `std::future` used for in C++ multithreading?
- To synchronize access to shared resources.
- To represent the result of an asynchronous operation that may not have completed yet.
- To manage the lifecycle of threads.
- To create barriers for synchronization.
Show answer
Answer: B. To represent the result of an asynchronous operation that may not have completed yet.
`std::future` objects are used to retrieve values from asynchronous operations (like those launched by `std::async`) or from promises. The `get()` method of a future will block until the result is available.
What is the primary role of `std::this_thread::sleep_for()`?
- To allow other threads to run by yielding the CPU.
- To pause the current thread for a specified duration.
- To terminate the current thread.
- To acquire a mutex.
Show answer
Answer: B. To pause the current thread for a specified duration.
`std::this_thread::sleep_for()` causes the currently executing thread to sleep (become dormant) for a specified duration. This is often used to limit CPU usage or introduce delays in concurrent operations.
What does the `std::once_flag` object do when used with `std::call_once`?
- It acts as a counter for function calls.
- It is a synchronization mechanism to track whether the associated function has already been executed.
- It stores the return value of the called function.
- It determines which thread will execute the function.
Show answer
Answer: B. It is a synchronization mechanism to track whether the associated function has already been executed.
The `std::once_flag` is passed to `std::call_once` to ensure that the target function is executed exactly one time across all threads. The `once_flag` internally manages the state to achieve this guarantee.
What is the primary purpose of `std::packaged_task` when it is invoked?
- To signal a condition variable.
- To execute the wrapped callable and store its result/exception in a shared state accessible via a future.
- To create a new thread.
- To acquire a mutex.
Show answer
Answer: B. To execute the wrapped callable and store its result/exception in a shared state accessible via a future.
When a `std::packaged_task` is invoked (called like a function), it executes the task it wraps. The result (or exception thrown) is then stored in an internal shared state, which can be retrieved by another thread using the `std::future` obtained from `get_future()` on the `packaged_task`.