Reputation: 18461
I came into a situation where I need to lock a resource (a std::queue
) between two processing threads.
The first thread needs to push
data to std::queue
, while the second thread is going to pop
that data out of the queue and process it.
I need to make sure both threads will not compete for my std::queue
.
As this is my first time using C++ locks, I came into different approaches: std::lock
and std::unique_lock
, but I don´t know which one to choose...
What is the difference between std::lock
and std::unique_lock
and how they should be used.
Thanks for helping.
Upvotes: 1
Views: 323
Reputation: 477100
std::lock
is an algorithm that locks a collection of lockable objects all at once in a specific way that avoids deadlocks.
std::unique_lock
is a class template that wraps a mutex and can be used as a scoped lock guard, similar to std::lock_guard
, but more powerful than the latter (it is itself lockable, can be unlocked early and can be moved around).
You probably want neither of those, but instead just use the good old std::lock_guard
.
Upvotes: 6