Usage of C++11 std::unique_lock<std::mutex> lk(myMutex); not really clear

375 views Asked by At

This is basically a concurrency program that implements the simulation of a salesman that has to serve some customers that are coming to his shop. Here is the code of class salesman:

class SalesMan
{
    public:
    Room *room; 
    std::unique_lock<std::mutex> *salesman; 
    Salesman(Room *r)
    {
        this->room = r;                         
        salesman = new std::unique_lock<std::mutex>(room->salesman,std::defer_lock_t());
    }
    void operator()()
    {
        while (true)
        {
            if (room->look() == 0) //checks if there are customers awaiting
            {
                std::unique_lock<std::mutex> lk(room->salesman); 
                room->chair.wait(lk); //salesman rests on the chair
            }


            room->waiting.notify_one();  
            room->serving.notify_one(); 
        }
    }
};

Room is a class that has got std::mutex salesman and the condition variables chair, waiting and serving. What I didn't clearly understand is what does the std::unique_lock<std::mutex> lk(room->salesman) do; does it initialize the mutex that is used by the condition variable or does it make the thread enter in a mutually exclusive part of code? Also, there's a class called Customer that in its constructor has the same lines of the constructor of salesman, but it does this with the unique_lock mutex:

salesman->lock()
*buy things*
salesman->unlock()

So what is the usage of salesman in the class "SalesMan" if we don't use lock/unlock functions?

0

There are 0 answers