[英]What is the correct way to sync variables between two threads in C++?
我有以下两个函数在两个不同的线程上运行。
#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
的值不相同。 我是否错过了会导致两个线程不同步的东西?
试试这个,看看它是否有帮助:
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;
}
具体来说,在你的整个方法中使用你的锁。 此外,您插入的额外大括号不会做任何事情——除非您在大括号内移动您的保护,然后它控制范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.