General Multithreading Question

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:

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?
Each thread has its own set of CPU registers.
Last edited on
so you mean to say if i have 3 threads, there should be 3 accumulators even on a single core machine? Sorry i didn't get you
Well, it is each core that has an accumulator. When a core switch thread, it has to first store the accumulator value somewhere in memory that can later be restored when switching back.
alright ! thanks.
Topic archived. No new replies allowed.