c++ - C++ Mutex 是否保证避免竞争条件?

标签 c++ multithreading

我正在编写一个简单的示例来测试 C++ 线程和互斥量:

#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;
}

执行后,所有值应该相同,但这是输出:

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

C++ 互斥锁真的保证互斥,还是我漏掉了什么?

最佳答案

5gon12eder 是对的。使用 -pthread 问题得到解决并且输出正确:

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

我很惊讶您在使用线程时需要为编译器使用“-pthread”选项,并且没有编译或链接错误。

PS:编译器为gcc,操作系统为Linux(g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4)

关于c++ - C++ Mutex 是否保证避免竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32552990/

相关文章:

java - 交换器似乎没有交换()

android - 如何保持发布版本的断言活跃

C++ 2D Vector 在 vector 中设置一个位置

c++ - size_t除以int类型转换规则

c++ - 访问给定的 future 后 boost::future<>.then() 中的错误访问

c# - 关闭前台线程的正确方法

c++ - 如何判断是使用<filesystem>还是<experimental/filesystem>?

java - oracle-jdbc数据库变更通知中出现空指针异常

java - Java 同步(锁定、条件)的奇怪行为

ios - 核心数据对象的顺序改变,核心数据合并后上下文之间不同