Go language lightweight threads Goroutine usage example

  • 2020-05-26 09:17:30
  • OfStack

This article illustrates the use of Goroutine as a lightweight thread in the Go language. Share with you for your reference. The details are as follows:

goroutine is a lightweight thread managed by the Go runtime environment.
go f(x, y, z)
Open a new goroutine execution
f(x, y, z)
f, x, y, and z are currently defined in goroutine, but f runs in the new goroutine.
goroutine runs in the same address space, so access to Shared memory must be synchronized. sync provides this possibility, but it is not often used in Go because there are other ways. (more on that later.)

package main
import (
    "fmt"
    "runtime"
)
func say(s string) {
    for i := 0; i < 5; i++ {
        runtime.Gosched()
        fmt.Println(s)
    }
}
func main() {
    go say("world")
    say("hello")
}

I hope this article has been helpful to your programming of Go language.


Related articles: