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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With