【发布时间】: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