Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ what happens when in one thread write and in second read the same object? (is it safe?) [duplicate]

What happens when in one thread write and in second thread read the same object? It would lead to application crash?

My idea is, on main thread save the data in to object or change the data from object and on second thread only read this data.

If I understand, the problem can be only while writing to object new value and reading in same time from same object, reading value will be old. But this is not problem for me.

I search my question and found this topic What happens if two threads read & write the same piece of memory but I am not sure if it apply for my question.

like image 370
Wanderer Avatar asked Jun 12 '18 09:06

Wanderer


People also ask

What will happen if multiple threads accessing the same resource?

Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.

Can two threads read memory at the same time?

Unlike with isolated programs, threads share the same memory space, so two threads can read and write anything in each other's memory at the same time. Threads each have their own registers and stack areas, but the stacks are each in their own area of the same memory space.

What happens when two threads call the same function?

Basically, there are no problems. Each function call has its own private set of local variables and will never interfere with other threads or other calls of the same function in the call stack. However, all resources that might be shared between threads are potentially dangerous.

Can two threads read the same variable?

A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.


1 Answers

Unless the object is atomic, the behaviour of one thread writing and another thread reading the same object is undefined.

Your current perception that the only issue is that state data could be read is not correct. You cannot assume that will be only manifestation of the undefined behaviour. In particular, you may well find that the value you read is neither the old nor the new value.

like image 186
Bathsheba Avatar answered Nov 14 '22 22:11

Bathsheba