簡體   English   中英

為什么這不是線程安全的?

[英]Why is this not thread-safe?

為什么這不是線程安全的? 據我了解,結果應該是一串100秒。

#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

int main()
{
    std::vector<int*> values(100, new int(0));
    std::vector<std::thread> threads;
    std::vector<std::mutex> mutexes(100);
    for (int i = 0; i < 100; i++)
    {
        threads.emplace_back([](int* v, std::mutex* m)
        {
            for (int j = 0; j < 100; j++)
            {
                std::lock_guard<std::mutex> guard(*m);
                (*v)++;
            }
        }, values[i], &mutexes[i]);
    }
    for (auto& t : threads) t.join();
    for (int i = 0; i < 100; i++)
    {
        std::lock_guard<std::mutex> guard(mutexes[i]);
        std::cout << (*(values[i])) << ' ';
    }
    std::cout << std::endl;
}

結果:

9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863

您只需要一個互斥鎖。 對於 100 個互斥鎖,每個線程將立即鎖定自己的互斥鎖,而不是等待其他線程,因此不會發生同步。

暫無
暫無

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

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