Search code examples
c++multithreadingmutexunique-lock

Passing mutex reference from main to a class


I need to work with the same mutex and unique_lock across the main function and class instances. However, I am having trouble assigning the mutex/unique_lock address to a class member variable (that is a mutex&).

This is what I have:

Worker.h

class Worker 
{
private:

    std::mutex &m_mu;
    std::unique_lock<std::mutex> &locker;

public:

    void start(std::mutex &mu, std::unique_lock<std::mutex> &locker);

};

Worker.cpp

void Worker::start(std::mutex &mu, std::unique_lock<std::mutex> &locker)
{
    this->mu = mu; // error 
    this->locker = locker; // error
}

I tried doing this->mu(mu); but that doesn't work either. Is there anything I can do to make this work?

Thanks.


Solution

  • You need to pass the mutex reference when you construct your class.

    Worker::Worker(std::mutex &mu, std::unique_lock<std::mutex> &locker)
    :m_mu(mu), locker(locker)
    {}
    

    That's the only place you can initialize a reference. Once it's constructed, you cannot change what it references.

    Why do you need the locker? The mutex makes the synchronization, the lock is just a RAII object to ease acquiring the mutex.