What do threads of the same process share, and what does each thread keep private?
Threads in one process share code, global data, the heap and open files. Each thread has its own stack, program counter, registers and thread ID.
Explain it simply
Think of roommates in one flat. They share the kitchen, fridge and Wi-Fi, but each has a personal bed, bag and phone. Threads in one process work the same way.
Shared by all threads in a process
- Code (text) segment
- Global and static variables
- Heap memory
- Open files and sockets
- Signal handlers and the process ID
Private to each thread
- Stack (local variables and function calls)
- Program counter
- Register values
- Thread ID and its own scheduling state
Example
int counter = 0; // global: shared by every thread
void *work(void *arg) {
int local = 0; // on this thread's own stack: private
local++;
counter++; // all threads touch the same variable
return NULL;
}Each thread gets its own local, so there is no conflict. But counter is one variable in shared memory. Two threads incrementing it at once can lose updates, which is why shared data needs a lock.
Sharing is also why creating a thread is cheaper than creating a process: no memory space has to be copied.
What to say in the interview
"Threads share the code, data, heap and open files of their process. Each has its own stack, registers and program counter. The shared part makes communication easy but needs locks; the private stack is why local variables are safe."
Common mistakes
- Saying threads share their stack. Each thread has its own.