简体   繁体   中英

What is the correct way to sync variables between two threads in C++?

I have the following two functions that are running on two different threads.

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

The number of stores is determined by the number of ranks the user run, each rank is considered a store. Most of the time when I run the program it runs successfully. But once in a while the values of the variables productinStock and productinStore on the two different threads are not the same. Am I missing something that would cause the two threads to not be synced?

Try this and see if it helps:

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

Specifically, use your lock guard on your entire method. Also, the extra braces you inserted don't do anything -- unless you move your guard inside the braces, then it controls scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM