goroutine details

content

1. Create a goroutine

1. Start a single coroutine

2. The problem of using goroutine

3. Start multiple goroutines

2. Use anonymous functions to create goroutines


1. Create a goroutine

        A Go program uses the go keyword to create a goroutine for a function. A function can be created by multiple goroutines, and one goroutine must correspond to one function.

go 函数名( 参数列表 )

        When a goroutine is created with the go keyword, the return value of the called function is ignored. If you need to return data in the goroutine, you need to use the channel (channel) feature, and pass the data out of the goroutine as the return value through the channel.

1. Start a single coroutine

func running() {
    fmt.Println("Hello Goroutine!")
}

func main() {
    go running() // 启动另外一个goroutine去执行hello函数
    fmt.Println("main goroutine done!")
}

        When the program starts, the runtime (runtime) will create a goroutine for the main() function by default. When the go running statement is executed in the goroutine of the main() function, the goroutine belonging to the running() function is created, and the running() function starts to execute in its own goroutine. At this point, main() continues to execute, and the two goroutines operate simultaneously through the Go program's scheduling mechanism.

 

2. The problem of using goroutine

The execution result this time only prints main goroutine done!, and does not print Hello Goroutine!. why?

1) When the program starts, the Go program creates a default goroutine (main coroutine) for the main() function.

2) When the main() function returns, the goroutine ends, and all goroutines started in the main() function will end together

So we have to find a way to make the main coroutine and other coroutines, the most simple and crude way is time.Sleep.

func main() {
    go hello() // 启动另外一个goroutine去执行hello函数
    fmt.Println("main goroutine done!")
    
    time.Sleep(time.Second) //停顿一秒,这种方法不好,见channel阻塞/死锁详解
}

3. Start multiple goroutines

var wg sync.WaitGroup

func hello(i int) {
    defer wg.Done() // goroutine结束就登记-1
    fmt.Println("Hello Goroutine!", i)
}
func main() {

    for i := 0; i < 10; i++ {
        wg.Add(1) // 启动一个goroutine就登记+1
        go hello(i)
    }
    
    wg.Wait() // 等待所有登记的goroutine都结束
}

Execute the above code multiple times, and you will find that the order of the numbers printed each time is inconsistent. This is because the 10 goroutines are executed concurrently, and the scheduling of goroutines is random.

2. Use anonymous functions to create goroutines

Goroutines can also be started for anonymous functions or closures after the go keyword.

go func( 参数列表 ){
    函数体
}( 调用参数列表 )

Create an anonymous function in the main() function and start a goroutine for the anonymous function. Anonymous functions have no parameters.

package main
import (
    "fmt"
    "time"
)

func main() {
    go func() {
        var times int
        for {
            times++
            fmt.Println("tick", times)
            time.Sleep(time.Second)
        }
    }()
    
    var input string
    fmt.Scanln(&input)
}

Summarize:

1) All goroutines will end together when the main() function ends

2) Although goroutine is similar to the concept of threads, it is not as detailed in terms of scheduling performance, and the degree of detail depends on the implementation and operating environment of the goroutine scheduler of the Go program.

Guess you like

Origin blog.csdn.net/demored/article/details/124116021