Possible Duplicate:
Are incrementers / decrementers (var++, var–) etc thread safe?
Can you describe for me, at the assembly code level, why incrementing a value from two different threads is not considered safe on a single core machine?
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.
Consider the instructions that might be generated for a statement like
i++. Of course this will depend upon your architecture/instruction set, but it will probably be something along the lines of:Now consider how multithreading would be implemented in an operating-system, regardless of how many cores the machine has. At the most basic level, the OS is going to need some facility to interrupt the execution of the current thread, save its state, and perform a context switch to a different thread. The OS has no automatic way of knowing which instructions inside of a user thread should be treated as an atomic operation, and has the ability to initiate a context switch between any two instructions.
So what happens if the OS performs a context switch from one thread to the other between
LOADandADD? Let’s say thatistarted out with a value of 0, sor0will be set to 0 when the first thread gets swapped out. The OS will save this value as part of that thread’s state. Now the second thread runs, and performs the sameLOADstatement. The value in memory is still 0, sor0gets 0 loaded into it again. The thread increments the value and writes it back to memory, setting the value ofito 1. Now the first thread resumes execution, and the operating-system restores the value ofr0to 0 as part of its context switch. The first thread now performs its increment, settingr0to 1, and the value of 1 gets stored iniagain. Now the value ofiis incorrect because two increments have been applied, but the value has only increased by 1.So in a nutshell, even though
i++is a single statement in a high-level language, it generates multiple assembly-language instructions, and those instructions will not be treated as atomic by the operating-system/runtime environment unless you add extra synchronization logic around them.