shared_ptr 中的竞争条件不会发生

Race condition in shared_ptr doesn't happen

为什么我的代码中没有任何竞争条件? 由于来源在这里:http://en.cppreference.com/w/cpp/memory/shared_ptr

If multiple threads of execution access the same shared_ptr without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur;

class base
{
public:
    std::string val1;
};

class der : public base
{
public:
    std::string val2;
    int val3;
    char val4;
};

int main()
{
    std::mutex mm;
    std::shared_ptr<der> ms(new der());

    std::thread t1 = std::thread([ms, &mm]() {
        while (1)
        {
        //std::lock_guard<std::mutex> lock(mm);

            std::string some1 = ms->val2;
            int some2 = ms->val3;
            char some3 = ms->val4;
            ms->val2 = "1232324";
            ms->val3 = 1232324;
            ms->val4 = '1';
        }
    });

    std::thread t2 = std::thread([ms, &mm]() {
        while (1)
        {
            //std::lock_guard<std::mutex> lock(mm);

            std::string some1 = ms->val2;
            int some2 = ms->val3;
            char some3 = ms->val4;
            ms->val2 = "123435";
            ms->val3 = 123435;
            ms->val4 = '3';
        }
    });

    std::shared_ptr<base> bms = ms;
    std::thread t3 = std::thread([bms]() {
        while (1)
        {
            bms->val1 = 434;
        }
    });

    while (1)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}

数据竞争不会导致编译失败;它们会产生未定义的行为。这种行为 可能 是 "works fine"。或者 "appears to work fine but subtly breaks something 12 minutes later"。或者 "immediately fails."

只是因为代码 看起来 有效并不意味着它确实有效。线程代码比任何其他类型的代码更是如此。

我建议您使用 valgrind 工具 - helgrind。 在调试多线程程序时,有时很难发现竞争条件。 要 运行 此工具,您需要在您的计算机上安装 valgrind 并 运行 使用:

valgrind --tool=helgrind ./Your_Complied_File arg1 arg2 ...