Home >Backend Development >Golang >How does golang function control the execution of goroutine?
The Go function controls Goroutine execution in the following ways: runtime.Goexit(): Forcefully terminates the current Goroutine. sync.WaitGroup: Wait for a group of Goroutines to complete. select{}: Allows a Goroutine to wait for one of multiple events and perform the corresponding action based on the first triggered event. context.Context: Can be used to pass deadlines or cancel requests to Goroutines.
How the Go function controls the execution of Goroutine
The Go programming language supports concurrency and is implemented using Goroutine (lightweight threads) concurrent. Goroutines can be created through functions and started at any time after creation. This article will introduce the different functions used to control Goroutine execution and provide some practical examples.
Function that controls Goroutine execution
Practical case
1. Terminate Goroutine
package main import ( "fmt" "runtime" "time" ) func main() { go func() { for { fmt.Println("Goroutine is running...") time.Sleep(1 * time.Second) } }() // 等待 10 秒后终止 Goroutine time.Sleep(10 * time.Second) runtime.Goexit() }
2. Use sync.WaitGroup to wait Goroutine
package main import ( "fmt" "sync" "time" ) func main() { var wg sync.WaitGroup // 创建 5 个 Goroutine for i := 0; i < 5; i++ { wg.Add(1) go func(i int) { fmt.Printf("Goroutine %d is running...\n", i) time.Sleep(1 * time.Second) wg.Done() }(i) } // 等待所有 Goroutine 完成 wg.Wait() }
3. Use select{} to respond to the event
package main import ( "fmt" "time" ) func main() { fmt.Println("Waiting for events...") // 创建两个 channel ch1 := make(chan string) ch2 := make(chan string) // 创建两个 Goroutine 向 channel 发送数据 go func() { time.Sleep(1 * time.Second) ch1 <- "Event from Channel 1" }() go func() { time.Sleep(2 * time.Second) ch2 <- "Event from Channel 2" }() for { select { case msg := <-ch1: fmt.Println(msg) return case msg := <-ch2: fmt.Println(msg) return } } }
4. Use context.Context to cancel Goroutine
package main import ( "context" "fmt" "time" ) func main() { // 创建一个 context ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // 创建一个 Goroutine go func() { for { select { case <-ctx.Done(): fmt.Println("Goroutine cancelled") return default: fmt.Println("Goroutine is running...") time.Sleep(1 * time.Second) } } }() // 等待 15 秒后取消 Goroutine time.Sleep(15 * time.Second) cancel() }
The above is the detailed content of How does golang function control the execution of goroutine?. For more information, please follow other related articles on the PHP Chinese website!