Matthew Yang
Matthew Yang

Reputation: 625

Will a thread use an old value passed in?

I just thought of this question and couldn't find an answer

If I pass a static non-primitive variable, say X, into a thread which starts at a later time (so one would assume the thread holds a reference to X), is there any possibility that when the thread starts, instead of reading X from memory, it may use the old value of X when X was passed to the thread

or a similar scenario like:

thread A runs and writes X = a to RAM, then gets blocked by IO

thread B reads X = a from RAM, queues a unit of work to A, which would use X

thread A resumes and writes X = b to RAM, then it finishes what it had left

...

thread A resumes and runs that unit of work queued to it, which would use X

Is it possible that X would have the value a?

If so, is it possible to happen in mainstream languages like C, C++, Java, C# on mainstream platforms? (all versions for jvm for java and all versions for .Net and Mono for C#)?

I would not expect this to happen, but rather curious if it would on any sort-of-popular platforms, causes maybe crazy compiler optimization, caching (always a possibility), extremely cheap hardware etc

Upvotes: 1

Views: 210

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61369

I think you are a bit confused. Programs don't read data from memory into... something else (seriously, where do you think it would go?). Its always read from memory.

All the time, every time. So no, your scenario is simply not possible. It will always have the updated value.

Quick disclaimer, variables/data can always be cached by the CPU to avoid RAM hits, so if the hardware didn't synchronize, this could happen, but its not an issue with the language/runtime. The software concept of "Memory" includes RAM, cache, and Virtual memory.

Upvotes: 2

SMA
SMA

Reputation: 37063

It's not about the object (concrete fully built) but the state of an Object. So let's say if you have counter within X that constitutes of State and yes if thread a writes to counter then it may happen thread B can't see the changes.

Upvotes: 0

Related Questions