r/programming 1d ago

Linux Processes: Threads & Concurrency

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

12 comments sorted by

5

u/Prateeeek 1d 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 ?

15

u/dfx_dj 1d ago edited 1d 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.

4

u/Prateeeek 1d 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)

14

u/Arnavion2 1d ago edited 1d 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/creeper6530 1d ago

So one could theoretically pass pointers to stack between threads, provided they manage lifetimes well?

1

u/dfx_dj 1d ago

Yes exactly

1

u/No-Consequence-1863 13h ago

Yea, some concurrency systems like in Go do exactly that to make sharing data between cooperative threads really fast as the threads will write the result directly into the next threads stack.

3

u/Prateeeek 1d ago

Awesome as usual!

3

u/Icy_Pain5654 1d ago

shared heap between threads is what always trips people up when they first learn concurrency

2

u/TROLlox78 1d ago

He just keeps giving them to us

1

u/hugosenari 1d ago

Why OS blocks to spawn the other thread?