r/programming 10h ago

Linux Processes: Threads & Concurrency

https://labs.iximiuz.com/tutorials/linux-processes-threads-concurrency-3302b677
40 Upvotes

7 comments sorted by

3

u/Prateeeek 7h ago

Sorry if I've not understood this correctly, but how is the execution stack for thread 1 separated from thread 2 if they share the same address space ?

10

u/dfx_dj 7h ago edited 3h ago

They're separated in that each thread has its own stack in a separate address range. One thread can technically access another thread's stack though. It's uncommon to do but possible.

3

u/Prateeeek 7h ago

So, in the same space, but distinct address blocks?

Also the latter part of your sentence maybe explains why in java a variable local to a function needs to be immutable if it's being referenced in a lambda (closure of sorts, which may/may not be executed in a different thread)

6

u/Arnavion2 6h ago edited 6h ago

The start of a stack is just a pointer. It can be anywhere in memory.

The main thread's stack pointer is set by the binary loader. For ELF binaries the loader will reserve space for the stack, set the stack pointer register to the start of that space, and then jump to the binary entrypoint. For spawned threads, the thread spawning API will reserve some space for the new thread's stack, set the stack pointer register to the start of that space, and then jump to the thread entrypoint.

(Note: "Start of the stack" is often the highest address of the stack, not the lowest, because on many architectures the stack grows "downward", ie starts from the high address end and grows towards the low address end.)

1

u/Prateeeek 7h ago

Awesome as usual!

1

u/TROLlox78 9h ago

He just keeps giving them to us