首页 > 解决方案 > 为什么这不是线程安全的?

问题描述

为什么这不是线程安全的?据我了解,结果应该是一串100s。

#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

标签: c++multithreading

解决方案


您只需要一个互斥锁。对于 100 个互斥锁,每个线程将立即锁定自己的互斥锁,而不是等待其他线程,因此不会发生同步。


推荐阅读