It depends on what you expect. The other answers are correct that, as a rule, standard C ++ containers are not thread safe, and, in addition, in particular, your code does not protect another thread, changing the container between your call to empty and acquiring a lock (but this matter is not related to thread safety vector::empty ).
So, to avoid any misunderstandings: Your code does not guarantee that items will be non-empty inside the block.
But your code can still be useful, since all you want to do is to avoid redundant castle creations. Your code does not offer guarantees, but may prevent the creation of unnecessary blocking. It will not work in all cases (other threads can still remove the container between your check and the lock), but in some cases. And if everything, after which you optimize by lowering the backup lock, then your code will achieve this goal.
Just make sure that any actual access to the container is protected by locks.
By the way, above, strictly speaking, the behavior is undefined : an STL implementation is theoretically allowed to change mutable members inside an empty call. This would mean that apparently harmless (because read-only) calling empty could cause a conflict. Unfortunately, you cannot rely on the assumption that read-safe calls are safe with STL containers.
In practice, however, I am sure that vector::empty will not modify any members. But already for list::empty I'm less sure. If you really need guarantees, either block every access or do not use STL containers.
Konrad Rudolph
source share