views:

66

answers:

2

I know that stacks are per thread, but registers are limited,like on IA32,only 8 registers.

So how are registers shared among threads?

A: 

For clarification, technically threads within a single process share a different portion of the process' address space. Each have their own state (it's set of registers, a stack, etc.) and it's all allocated within the process' address space. They don't have their own address space.

When the operating system performs a context switch, it saves all the general purpose registers onto some known location (the context). Then the process that will be using the CPU next will have its saved registers restored so it may execute. This happens every time a new process needs control of the CPU, switch out and switch in.

Jeff M
TL/DR: They aren't shared.
Christian Mann
What do you mean by `TL/DR`?
justnobody
@Christian: It might just be a confusion of terms. They don't share values in registers yes but they do share time using the hardware. The register [usage] are shared among threads (and other running processes).
Jeff M
Too long ; Didn't read, but that's too long, so I just type tl;dr.
Christian Mann
Completely wrong: 'They don't have their own new stack.'. Yes they do. 'It's all within their process' stack'. No it isn't. It's all within the process's *data segment*. Not 'its stack' - there is no such thing. Register save/restore happens across thrads as well as processes.
EJP
@EJP: In my side note, I said "stack" but entirely meant address space. I just tried to address the OP's first statement using his words. You should have known what I meant instead of discrediting my entire answer, could have just pointed that out and I would have corrected that.
Jeff M
There were several problems in your answer. I noted them. There still are.
EJP
+3  A: 

Registers are used by the CPU when it's currently running a particular thread. When the OS decides to switch from one thread to another, the OS saves the current values of all the register into a private memory area specific to the first thread. Before the second thread starts running, the OS loads the values of all the registers from its saved area. This is called a context switch.

Greg Hewgill