Question 18
Back to Exercise
What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)
#include <iostream>
#include <mutex>
int main() {
std::mutex m;
std::unique_lock<std::mutex> lock(m, std::defer_lock); // associated, but not locked yet
std::cout << lock.owns_lock();
lock.lock();
std::cout << lock.owns_lock();
lock.unlock(); // unlock early…
std::cout << lock.owns_lock();
std::unique_lock<std::mutex> other(m, std::try_to_lock);
std::cout << other.owns_lock() << '\n'; // …so another lock can take it
return 0;
}
- A 0101 Correct
- B 1101
- C 0100
- D 1111
Correct Answer: Option A
unique_lock can be created unlocked (defer_lock), locked and unlocked manually, and tells you whether it holds the mutex. It still unlocks automatically at scope end if it owns it.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!