Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c++ - Why is this not thread-safe?

Why is this not thread-safe? From my understanding, the result should be a string of 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;
}

Result:

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
question from:https://stackoverflow.com/questions/65933150/why-is-this-not-thread-safe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need just a single mutex. With 100 mutexes each thread will immediately lock its own mutex instead of waiting for other threads so no sync happens.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...