2

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.

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • You might as well be interested in [scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock) which is available in c++17. – Tony Tannous Sep 13 '19 at 21:33

0 Answers0