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

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -