简体   繁体   中英

Why do I need multiple mutexes?

I am currently looking at a code example below (also can be found here ).


#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex m_a, m_b, m_c;
int a, b, c = 1;
void update()
{
    {   // Note: std::lock_guard or atomic<int> can be used instead
        std::unique_lock<std::mutex> lk(m_a);
        a++;
    }
 
    { // Note: see std::lock and std::scoped_lock for details and alternatives
      std::unique_lock<std::mutex> lk_b(m_b, std::defer_lock);
      std::unique_lock<std::mutex> lk_c(m_c, std::defer_lock);
      std::lock(lk_b, lk_c);
      b = std::exchange(c, b+c);
   }
}
 
int main()
{
  std::vector<std::thread> threads;
  for (unsigned i = 0; i < 12; ++i)
    threads.emplace_back(update);
 
  for (auto& i: threads)
    i.join();
 
  std::cout << a << "'th and " << a+1 << "'th Fibonacci numbers: "
            << b << " and " << c << '\n';
}

Here, I am wondering why this example uses multiple mutexes m_a, m_b, m_c .

For instance,

  1. Can I only use m_a, m_b and do the following?
    {
        std::unique_lock<std::mutex> lk(m_a);
        a++;
    }

    {
      std::unique_lock<std::mutex> lk(m_b);
      b = std::exchange(c, b+c);
   }
  1. Or, can I only use m_a and do the following?
    {
        std::unique_lock<std::mutex> lk(m_a);
        a++;
    }

    {
      std::unique_lock<std::mutex> lk(m_a);
      b = std::exchange(c, b+c);
    }

What is the advantage of using multiple mutexes? I found that all three works identically on my computer.

Thank you in advance!

Assume you have more code, code that modifies only b and code that only reads only c.

Now both of those can run in parallel. If you only have one mutex protecting b and c as a pair then they would block each other.

Overall this looks like an example how to acquire multiple locks and other code that shows why multiple locks would be a good thing are simply missing for simplicity sake.

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