lundi 28 août 2017

One mutex vs Multiple mutexes. Which one is better for the thread pool?

Example here, just want to protect the iData to ensure only one thread visit it at the same time.

struct myData;
myData iData;

Method 1, mutex inside the call function (multiple mutexes could be created):

    void _proceedTest(myData &data)
    {
       std::mutex mtx;
       std::unique_lock<std::mutex> lk(mtx);
       modifyData(data);
       lk.unlock;
    }

    int const nMaxThreads = std::thread::hardware_concurrency();
    vector<std::thread> threads;
    for (int iThread = 0; iThread < nMaxThreads; ++iThread)
    {
        threads.push_back(std::thread(_proceedTest, iData));
    }

    for (auto& th : threads) th.join();

Method2, use only one mutex:

    void _proceedTest(myData &data, std::mutex &mtx)
    {
       std::unique_lock<std::mutex> lk(mtx);
       modifyData(data);
       lk.unlock;
    }
    std::mutex mtx;
    int const nMaxThreads = std::thread::hardware_concurrency();
    vector<std::thread> threads;
    for (int iThread = 0; iThread < nMaxThreads; ++iThread)
    {
        threads.push_back(std::thread(_proceedTest, iData, mtx));
    }

    for (auto& th : threads) th.join();

  1. I want to make sure that the Method 1 (multiple mutexes) ensures that only one thread can visit the iData at the same time.
  2. If Method 1 is correct, not sure Method 1 is better of Method 2? Thanks!

Aucun commentaire:

Enregistrer un commentaire