C++'s std::mutex
does not have a move constructor. There is a good reason for that. Basically, move constructors themselves are not generally thread safe, and the whole point of a mutex is that multiple threads will be trying to access it simultaneously.
An unfortunate implication of this is that a mutex cannot be placed into a container directly. Containers need the ability to safely move their contents around, and you can't do that with a mutex.
The easy way out is to just protect the entire container with a single separate mutex. But suppose I want finer-grained control than that? If I'm implementing a database via a container (eg: std::map
), it seems reasonable to want the ability to lock individual records, not just the whole database.
The next thing that comes to mind is to hack around the problem by using std::unique_ptr
. That would compile, but it doesn't really change the basic problem, does it? The scenario where there's a problem with move is where thread1
makes a container change that causes an entry move while thread2
is in the middle of using that container entry. In this scenario, thread2
could just as easily end up holding a destructed entry or smart pointer. It seems like no matter what, you end up having to lock the entire container with a mutex before doing anything.
It seems like there ought to be a known idiom for doing these kinds of things.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…