Take a boolean value. One thread is trying to assign a pre-determined value to it, and at exactly the same time another thread is trying to read it. What happens?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This depends on the architecture and language in question. In practice, this typically means you’ll have a race condition, and the “read” value may be the old or new value.
It’s more interesting if two threads to try write to the same variable at the same time – if one writes
falseand the othertrue, the actual resulting variable may end up with either value.In order to guarantee proper access, a memory barrier needs to be in place. This is especially true if dealing with multiple processors or even multiple cores, as the CPU cache lines need to be invalidated after a thread writes in order for a separate thread to read a value. Most languages have support for this in one form or another – for example, in C#, you can flag a variable as volatile in order to assist in this, but explicit synchronization (ie: locking) is typically still required.
Also, if the variable write is not a single CPU instruction (ie: using an interlocked operation or similar), care must be taken to explicitly synchronize the access for read and write – otherwise, you can (on some architectures) get the variable in a third, indeterminate state.