Threads and Source Language Statements

It is possible for a single source-language statement to be interrupted in mid-statement by another thread. The statement: i++; might involve three machine language instructions: loading a variable from storage into a register (if it is not already in a register); incrementing the register contents; and storing the result back to memory. If i is a double, or a pointer to struct, for example, the increment itself may be broken up into several machine language instructions. The thread may be interrupted at any instruction's completion point by another thread that also uses or changes the same variable, if you have not used a semaphore to lock during the increment.

Even if the machine code for a simple statement is a single instruction, you should avoid relying on this fact to provide data integrity. An increment of an integer variable requires a load, increment, and store; the load may have occurred on an earlier use of the variable within the same thread, and the store may occur some time later after another use of the variable. Thus the increment statement may only have a single instruction associated with it in the assembly listing, but another thread's modifying that variable between the load and increment, or the increment and store, affects the data integrity of the variable.



Debugging Threads