c++ - 仍然存在与 boost::mutex 的竞争条件

标签 c++ boost mutex boost-thread

我正在尝试一个示例,它会导致竞争条件应用互斥锁。然而,即使有互斥量,它仍然会发生。怎么了?这是我的代码:

#include <iostream>
#include <boost/thread.hpp>
#include <vector>
using namespace std;
class Soldier
{
private:
  boost::thread m_Thread;
public:
  static int count , moneySpent;
  static boost::mutex soldierMutex;   
  Soldier(){}
  void start(int cost)
  {
    m_Thread = boost::thread(&Soldier::process, this,cost);
  }

  void process(int cost)
  {
    {
    boost::mutex::scoped_lock lock(soldierMutex);
    //soldierMutex.lock();
    int tmp = count;
    ++tmp;
    count = tmp;
    tmp = moneySpent;
    tmp += cost;
    moneySpent = tmp;  
   // soldierMutex.unlock();
    }
  }  

  void join()
  {
    m_Thread.join();
  }
};

int Soldier::count, Soldier::moneySpent;
boost::mutex Soldier::soldierMutex;

int main()
{
  Soldier s1,s2,s3;
  s1.start(20);
  s2.start(30);
  s3.start(40);
  s1.join();
  s2.join();
  s3.join();
  for (int i = 0; i < 100; ++i)
    {
      Soldier s;
      s.start(30);
    }
  cout << "Total soldier: " << Soldier::count << '\n';
  cout << "Money spent: " << Soldier::moneySpent << '\n';
}

最佳答案

看起来您没有等待循环中启动的线程完成。将循环更改为:

 for (int i = 0; i < 100; ++i)
 {
   Soldier s;
   s.start(30);
   s.join();
 }

编辑以进一步解释

您看到的问题是打印出的值是错误的,因此您假设线程中存在竞争条件。事实上,当您打印值时,比赛就发生了——它们是在并非所有线程都有机会执行的情况下打印的

关于c++ - 仍然存在与 boost::mutex 的竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241350/

相关文章:

C++ SDK WFP 标注函数

c++ - 类似于嵌套互斥体但更通用的东西?

c++ - 使用带参数的 Boost::Thread 时出现编译器错误

c - 通过线程进行多次访问导致数据丢失的搜索示例(C 语言)

c++ - pthread_mutex_lock 上的段错误

c++ - 多线程类中互斥体可能出现段错误

c++ - cpp中的映射字符串

c++ - 模板代码中的转发引用与 const 左值引用

c++ - 在打印机上打印(windows平台32位)

c++ - 当我安装了多个 Visual Studio 版本时,如何使用 Visual Studio 2008 构建 boost?