Yurii Komarnytskyi
Yurii Komarnytskyi

Reputation: 173

Race condition in shared_ptr doesn't happen

Why there is no any race condition in my code? Due to source here: 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));
    }
}

Upvotes: 0

Views: 689

Answers (2)

Rafa_G
Rafa_G

Reputation: 45

I would recommend you to use valgrind tool - helgrind. It is very hard to find race conditions sometimes when debugging multi-threading programs. To run this tool you need to have valgrind on your computer and run it using:

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

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473212

Data races do not yield compilation failure; they yield undefined behavior. That behavior could be "works fine". Or "appears to work fine but subtly breaks something 12 minutes later". Or "immediately fails."

Just because code appears to work doesn't mean it actually does. This is more true for threading code than any other kind.

Upvotes: 3

Related Questions