3

I have a simple question about Linux threads and processes.

The process in Linux has a separate virtual address space which consists of:

- stack - heap - bss - code/text - data 

A process can have multiple threads inside them. I understand that they do share the address space of the process.

However, since the function calls that are executed by different threads can be different, does a thread have a separate stack segment?

1
  • Yes, each thread has it's own stack, etc. etc. Commented Aug 26, 2014 at 23:18

2 Answers 2

2
  1. Threads share all the memory segments, including the stack segment.
  2. Each thread has a separate stack.

Both statements are true. I know they sound like a contradiction.

The first thread's stack uses the so-called "stack segment". It's allocated by the kernel.

# cat /proc/self/maps ... 7fffbe0b0000-7fffbe0d1000 rw-p 00000000 00:00 0 [stack] ... 

Threads created later (e.g. created by pthread_create() or clone(CLONE_VM)) use the heap (or private anonymous mmap which is the same as heap in every ways) as their stack. It's allocated by the user program and passed to clone().

In short, each thread uses a separate stack. All the threads can read/write every other threads' stack.

Sign up to request clarification or add additional context in comments.

8 Comments

In which case the "stack segment" register probably doesn't point to the process's stack segment (in any but the original thread).
@BenVoigt: The "stack segment" register is a segmented-memory concept from old x86 and is not applicable to Linux or any modern OS. On x86 Linux, the stack segment register is set to the same value as the data segment register, and both refer to a protected mode selector for the full 4GB linear memory range with zero offset. The "stack segment" has no relation to what portion of this linear memory is actually being used for the stack.
@BenVoigt exactly. Thread X's stack pointer (e.g. esp) points to memory region Y is what I meant by thread X USES Y as its stack.
@R.., I think what BenVoigt meant is stack pointer, not stack segment. Nobody care about segment registers now.
@WuYongzheng - exactly the answer that I was looking for.
|
1

Yes, under the POSIX threading model, each thread has its own stack.

4 Comments

does this mean that there is a separate area in the stack segment reserved for each thread in the process? AFAIK the switching between the threads is done by the process itself without interference from the OS scheduler?
@liv2hak wot? Thread management IS the OS kernel scheduler/dispatcher responsibility.
@liv2hak: The answer to the question you linked explains that Linux does not use userspace thread scheduling (and in fact, it's basically impossible to implement POSIX threads that way due to signal and blocking syscall semantics).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.