You did not specify what the type of the mutex variable is, but provided that it is std::mutex (or something similar to guarantee mutual exclusion), the compiler cannot perform many optimizations. This way, you donβt have to worry about optimizing the return value or some other optimization that allows you to execute a size() request outside the mutex block.
However, as soon as the mutex lock is released, another waiting thread can freely access the vector and possibly mutate it, thus changing its size. Now the number returned by your function is deprecated. As Mats Peterson says in his answer, if this is a problem, then the mutex lock should be received by the caller getNumber() and held until the caller is done using the result. This ensures that the size of the vector does not change during the operation.
The explicit call to mutex::lock , followed by mutex::unlock , quickly becomes impracticable for more complex functions related to exceptions, multiple return statements, etc. A simpler alternative is to use std::lock_guard to obtain a mutex lock.
int getNumber() { std::lock_guard<std::mutex> l(mutex);
source share