0

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?

3
  • std::unique_lock<std::mutex> locks the mutex in its constructor, and unlocks in its destructor. Jun 7, 2015 at 23:15
  • 3
    Storing a std::unique_lock as a data member (much less a pointer) is questionable. You probably wanted to use a std::mutex instead.
    – David G
    Jun 7, 2015 at 23:23
  • Relevant links: RAII, std::unique_lock, std::condition_variable::wait
    – David G
    Jun 7, 2015 at 23:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.