jeudi 20 octobre 2016

C++ class with static mutex & racing condition

I have this C++ class with static mutex as private member of the class to protect cout in another public function of the class. But when I call object of the class from two threads I get a racing condition. Not sure why ?

class ThreadSafePrint
{
  public:
      void myprint(int threadNumber)
      {
        std::lock_guard<std::mutex> gaurd(mymutex);
        cout <<"Thread " << threadNumber << endl;
      }
  private:
      static std::mutex mymutex;
};

std::mutex ThreadSafePrint::mymutex;


int main()
{
    ThreadSafePrint obj;

    std::vector<std::thread> workers;

    int threadNumber;
    // create 2 threads and pass a number 
    for(int i=0; i<2;++i)
    {
      // threadNumber = 0 for 1st thread
      if(i==0)
      {
          threadNumber = i;
      }
      // threadNumber = 1 for 2nd thread
      if(i==1)
      {
          threadNumber = i;
      }

      workers.push_back(std::thread([&obj,&threadNumber]()
      {
          obj.myprint(threadNumber);
      }));

    }

    // join all threads
    std::for_each(workers.begin(), workers.end(),[](std::thread & th)
    {
            th.join();
    });

    return 0;
    }

Here are some results:

>> ./mythreads
Thread 1
Thread 1
>> ./mythreads
Thread 0
Thread 0

Aucun commentaire:

Enregistrer un commentaire