Difference in concept
- Process
- program that currently running
when program in disk load on memory, it become process
- program that currently running
- Thread
- basic unit of CPU to execute task
- process contains one or more threads
Difference in structure
- Process has Code, Data, Stack, Heap, PCB(ID, state, PC, memory limits, Register, priority, files, etc.)
- Thread has Stack, TCB(ID, state, PC, SP, Register, etc.)
Multithread in Golang
This case is when you run Golang executable files with three go-routines which is user-level thread.
And these OS kernel thread is matched with goroutine(user-level thread) with this features
To get more information about goroutine, please check my last posting here
Back to the subject, Users can manage their process with Goruntime or Thread-libraries. And how about OS level?
They manage their process with above lifecylce
Implementing the Stack in Golang
Imagin that your stack in Golang program is exceeded. How can you manage your stack? Here is 2 options.
- Add stack segment with linked list
- Create larger stack and copying stack
The first option seems very nice, but it runs into certain serious performance problems. Creating more stack doesn’t occur problems, but it will be when you shrink your segment stack just after you finish your function(stack frame). This will take a lot of cost when it is repeated inside the loop. This is called hot split
problem.
Thus, Golang choose second option.
Golang had to choose 2 option in many reasons.
First reason : Golang leverage contignous memory allocations for their Garbage Collection. Which means that Golang have to store their local variable in contiguous way(first option doesn’t store their variable contiguously).
Second reason : As I said, it has performance problems(hot split
).
To make contiguous stacks, Golang have 4 stage.
- create a new, somewhat larger stack
- copy the contents of the old stack to the new stack
- re-adjust every copied pointer to point to the new addresses
- destroy the old stack
To get more information about how Golang managing their stacks, see https://go.dev/doc/go1.4#runtime, https://without.boats/blog/futures-and-segmented-stacks/
References
- https://www.scaler.com/topics/operating-system/process-control-block-in-os/
- https://blog.cloudflare.com/how-stacks-are-handled-in-go/