【问题标题】:What is the correct way to sync variables between two threads in C++?在 C++ 中的两个线程之间同步变量的正确方法是什么?
【发布时间】:2023-04-01 23:42:01
【问题描述】:

我有以下两个函数在两个不同的线程上运行。

#include <mutex>

std::mutex mu;
int productinStock = 100;
int productinStore = 20;

//Running on main thread: Function called when Purchase happen
void UpdateStoreStock()
{
    UpdateNumProduct();
    UpdateSalesPerMonth();
    std::lock_guard<std::mutex> guard(mu);
    {
       if(productinStore == 0 && 0 < productinStock)
          OrderProduct();
    }

}

//Running on second thread: Function to Recv product from other stores
void RecvProduct(int num)
{
   std::lock_guard<std::mutex> guard(mu);
   {
       productinStore = num;
       productinStock = productinStock - num;
      
   }
}

商店的数量由用户运行的排名数决定,每个排名被视为一个商店。 大多数情况下,当我运行程序时,它会成功运行。但有时两个不同线程上的变量productinStock 和productinStore 的值并不相同。 我是否遗漏了一些会导致两个线程不同步的内容?

【问题讨论】:

  • 由于您没有显示UpdateNumProduct 或UpdateSalesPerMonth,我们应该如何猜测它们中的任何一个是否在不持有锁的情况下改变了这些变量?或者没有显示任何其他代码,因为这显然不是一个完整的示例?

标签: c++ multithreading thread-safety mpi mutex


【解决方案1】:

试试这个,看看是否有帮助:

void UpdateStoreStock()
{
    std::lock_guard<std::mutex> guard(mu);
    UpdateNumProduct();
    UpdateSalesPerMonth();
    if(productinStore == 0 && 0 < productinStock) {
       OrderProduct();
    }
}

//Running on second thread: Function to Recv product from other stores
void RecvProduct(int num)
{
   std::lock_guard<std::mutex> guard(mu);
   productinStore = num;
   productinStock = productinStock - num;
}

具体来说,在你的整个方法中使用你的锁保护。此外,您插入的额外大括号不会做任何事情 - 除非您将后卫移动到大括号内,否则它会控制范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    相关资源
    最近更新 更多