簡體   English   中英

std::shared_mutex 不與執行 lock_shared() 的線程一起縮放

[英]std::shared_mutex not scaling with threads doing lock_shared()

我編寫了一個簡單的程序來測試std::shared_mutex在多個循環lock_shared()的線程中的性能。 但從結果來看,它似乎並沒有隨着添加更多線程而擴展,這對我來說真的沒有意義。

您可能會爭辯說這是因為stopFlag限制了性能,所以第二個 for 循環測試增加本地計數器,這在開始時幾乎是完美的縮放

注釋中的結果是使用帶有Release標志的MSVC編譯的。

int main()
{
    const auto threadLimit = std::thread::hardware_concurrency() - 1; //for running main() 
    struct SharedMutexWrapper
    {
        std::shared_mutex mut;
        void read()
        {
            mut.lock_shared();
            mut.unlock_shared();
        }
    };
    /*Testing shared_mutex */
    for (auto i = 1; i <= threadLimit; ++i)
    {
        std::cerr << "Testing " << i << " threads: ";
        SharedMutexWrapper test;
        std::atomic<unsigned long long> count = 0;
        std::atomic_bool stopFlag = false;
        std::vector<std::thread> threads;
        threads.reserve(i);
        for (auto j = 0; j < i; ++j)
            threads.emplace_back([&] {unsigned long long local = 0; while (!stopFlag) { test.read(); ++local; } count += local;  });
        std::this_thread::sleep_for(std::chrono::seconds{ 1 });
        stopFlag = true;
        for (auto& thread : threads)
            thread.join();
        std::cerr << count << '\n';
    }
/*
Testing 1 threads: 60394076
Testing 2 threads: 39703889
Testing 3 threads: 23461029
Testing 4 threads: 16961003
Testing 5 threads: 12750838
Testing 6 threads: 12227898
Testing 7 threads: 12245818
*/
    for (auto i = 1; i <= threadLimit; ++i)
    {
        std::cerr << "Testing " << i << " threads: ";
        std::atomic<unsigned long long> count = 0;
        std::atomic_bool stopFlag = false;
        std::vector<std::thread> threads;
        threads.reserve(i);
        for (auto j = 0; j < i; ++j)
            threads.emplace_back([&] {unsigned long long local = 0;  while (!stopFlag) ++local; count += local; });
        std::this_thread::sleep_for(std::chrono::seconds{ 1 });
        stopFlag = true;
        for (auto& thread : threads)
            thread.join();
        std::cerr << count << '\n';
    }
/*
Testing 1 threads: 3178867276
Testing 2 threads: 6305783667
Testing 3 threads: 9388659151
Testing 4 threads: 12472666861
Testing 5 threads: 15230810694
Testing 6 threads: 18130479890
Testing 7 threads: 20151074046
*/
}

在共享互斥鎖上放置讀鎖會修改該互斥鎖的 state。 您的所有線程都只嘗試更改共享互斥鎖 object 的 state 。 所以當然,這段代碼的擴展性很差。

共享互斥鎖的意義在於允許訪問未按比例修改的共享數據。 您無權訪問未修改的共享數據。 因此,您沒有在這里測量共享互斥鎖的任何有益屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM