fmrico
fmrico

Reputation: 73

Does C++ Mutex guarantee avoiding race conditions?

I am programming a simple example to test C++ Threads and Mutexes:

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

const int num_th = 50;
const int num_vals = 20;
const int num_it = 1000;

class MyVector {
 public:
  MyVector(int size): vals_(size, 0), idx_(0), mtx_() {}

  void inc() 
  {
    mtx_.lock();
    for(int i=0; i<num_it; i++)
    {
       vals_[idx_]++;
       idx_= (idx_+1) % num_vals;
    }
    mtx_.unlock();
  }

  int getVal(int idx) {return vals_[idx];}

private:
  std::mutex mtx_;
  int idx_;
  std::vector<int> vals_;
};


int main(int argc, char *argv[])
{
  MyVector m(num_vals);

  std::thread t1[num_th];
  for(int i=0; i<num_th; i++)
     t1[i] = std::thread(&MyVector::inc, &m);

  for(int i=0; i<num_th;i++)
     t1[i].join();

  for(int i=0; i<num_vals; i++)
    std::cout<<" "<<m.getVal(i);

  return 0;
}

After execution, all the values should be the same, but this is the output:

 2053 2063 2054 2038 2029 2038 2036 2043 2048 2049 2048 2055 2055 2050 2050 2051 2051 2055 2042 2066

Does C++ Mutexes really guarantee mutual exclusion, or did I miss something?

Upvotes: 0

Views: 586

Answers (1)

fmrico
fmrico

Reputation: 73

5gon12eder is right. With -pthread the problem is solved and the output is correct:

 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500 2500

I'm surprised you need to use the "-pthread" option to the compiler when using threads, and there are not compilation or linking errors.

PS: The compiler is gcc and the OS is Linux (g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4)

Upvotes: 1

Related Questions