I have worked on multithreading (in Qt) but i lack an in-depth knowledge. I think that the run-time never duplicates an execution code. A function will remain in precisely one memory location which all callers or object will use to invoke it. In multithreading i read that each thread gets its own stack, Instruction Pointers and so on. Let’s say we have a global function which translates to assembly algorithm like this:
//GlobalFunction()
instruction 1 : move value 4 into accumulator
instruction 2 : add 5 to content of accumulator
instruction 3 : subtract 1 from content of accumulator
//some more stuff and function returns
//thread 1
call GlobalFunction()
//thread 2
call GlobalFunction()
now maybe the instruction pointer of thread 1 points to instruction 3 while thread 2 gets the slice and executes instruction 1. After this thread 1 executes instruction 3. Won’t the accumulator data be corrupted for it? If so then why do functions using only non-static local variables do not require locking in multithreaded environment?
P.S: Also i suppose a single instruction is atomic not a group of instructions, so implementation might not get a chance of flushing the register data out into some storage location before executing instruction of another thread.
While there is only one set of registers on a CPU (for simplicity, I’m assuming a single core system), the system manages the register file such that each thread has it’s own separate register state – when the OS switches from one thread to another, the first thread’s registers are saved and the second thread’s saved registers are restored.
For automatic/stack variables each thread gets it’s own stack, so unless the thread does something to explicitly share such a variable (by passing the address or a reference to another thread), those variables are not shared and so are thread-safe.