c++ - Do I need to use volatile keyword if I declare a variable between mutexes and return it? -
let's have following function.
std::mutex mutex; int getnumber() { mutex.lock(); int size = somevector.size(); mutex.unlock(); return size; }
is place use volatile
keyword while declaring size? return value optimization or else break code if don't use volatile? size of somevector
can changed of numerous threads program have , assumed 1 thread (other modifiers) calls getnumber()
.
you haven't mentioned type of mutex
variable is, assuming std::mutex
(or similar meant guarantee mutual exclusion), compiler prevented performing lot of optimizations. don't need worry return value optimization or other optimization allowing size()
query being performed outside of mutex block.
however, mutex lock released, waiting thread free access vector , possibly mutate it, changing size. now, number returned function outdated. mats petersson mentions in answer, if issue, mutex lock needs acquired caller of getnumber()
, , held until caller done using result. ensure vector's size not change during operation.
explicitly calling mutex::lock
followed mutex::unlock
becomes unfeasible more complicated functions involving exceptions, multiple return statements etc. easier alternative use std::lock_guard
acquire mutex lock.
int getnumber() { std::lock_guard<std::mutex> l(mutex); // lock acquired int size = somevector.size(); return size; } // lock released automatically when l goes out of scope
Comments
Post a Comment