samedi 20 août 2016

C++ Pass Mutex By Reference for Different Instances

I want to share a mutex between different instances of a class, whose functions are running as threads. Is the way I have written it okay? (I don't think I need to be using a shared_mutex, although that might be better practice. Would I pass that in the same way?)

class A
{
 public:

     // Execute some work that locks some piece of data by acquiring the mutex.
     void execute(std::mutex & myMutex);
}

class B
{

 public:
     void execute(std::shared_ptr<A> a)
     {

        //   Create the Threads for execution.
        std::thread t(&B::runThread, a);

        t.join();            
     };

     void runThread(std::shared_ptr<A> a)
     {
         a->execute(theMutex);
     }



 private:

 //   The Mutex to share with the threads.
 std::mutex theMutex;

}

Aucun commentaire:

Enregistrer un commentaire