dongshilve4392
dongshilve4392
2017-10-26 02:15

goroutine和线程之间的区别

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douquan2023 douquan2023 4年前

    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”.

    点赞 评论 复制链接分享

相关推荐