Search code examples
multithreadinggogoroutine

the difference between goroutine and thread


I'm a newbie on Golang and I just learnt about the conception Goroutine with an example below:

package main

import "fmt"

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {    
    f("direct")
    go f("goroutine")
    go f("goroutine2")
    go func(msg string) {
        fmt.Println(msg)
    }("going")
    var input string
    fmt.Scanln(&input)
    fmt.Println("done")
}

Here is one result of execution:

direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine2 : 0
goroutine2 : 1
goroutine2 : 2
goroutine : 1
goroutine : 2
going

done

I can see that goroutine and goroutine2 appeared alternately. So for me it looks like the multi-threading.
I've been told that Goroutine is lighter than thread. So I just want to know what is exactly the difference between them, why doesn't Go use the routine instead of multi-thread?


Solution

  • Thread is a natural OS object it’s have enough. Threads manipulations are expensive operations. They require switch to kernel return back, save and restore stack and so on. Many servers used threads but it’s unreal to keep a lot of threads and do not go out of resources. Also there’s a special task to synchronize them.

    So new concept emerged - coroutine or coprogram. They could be imagined as parts of execution path between synchronization points: input-output, send-receive so on. They are very light and could be better orchestrated

    So “threads but better”.