Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Difference in concept

  • Process
    • program that currently running

      when program in disk load on memory, it become process

  • 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. a

And these OS kernel thread is matched with goroutine(user-level thread) with this features

goroutine

To get more information about goroutine, please check my last posting here

Goroutine structure and behavior

Back to the subject, Users can manage their process with Goruntime or Thread-libraries. And how about OS level?

processlifecycle

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.

  1. Add stack segment with linked list
  2. Create larger stack and copying stack

stack_overflow stack_overflow2 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.

  1. create a new, somewhat larger stack
  2. copy the contents of the old stack to the new stack
  3. re-adjust every copied pointer to point to the new addresses
  4. 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