I'm writing a simple class in where I need to read with getSample()
every 1 second:
class ProfilerVariable
{
public:
//To be executed at the end of the profiling period
void profile() {
std::unique_lock<std::mutex> lock{mutex};
sample = counter;
}
//return is thread-safe????
T getSample() {
std::unique_lock<std::mutex> lock{mutex};
return sample;
}
//Value to be increased at every profile call
T counter;
//Value to store the result of the accumulated counter at the end of profile period
private:
T sample;
std::mutex mutex;
};
Since this isn't possible:
T getSample() {
mutex.lock();
return sample;
mutex.unlock();
}
I used unique_lock(). But what happens first: unique_lock destruction and therefore the mutex unlock, or the function returns first?
I could do:
T getSample() {
std::unique_lock<std::mutex> lock{mutex};
T _sample = sample
return _sample;
}
or
T getSample() {
mutex.lock()
T _sample = sample
mutex.unlock();
return _sample;
}
but I'm still curious on what happens in the unique_lock case.