Yurii Komarnytskyi Yurii Komarnytskyi - 1 month ago 6
C++ Question

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));
}
}

Answer Source

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.