Goroutine in Go language can be managed in the following ways: 1. Create Goroutine: Use the "go" keyword. 2. Wait for the Goroutine to exit: use WaitGroup. 3. Cancel Goroutine: use context.Context and context.WithCancel. In terms of scheduling, Go uses a preemptive scheduling algorithm, but the runtime.Gosched() function can be used to trigger cooperative scheduling.
Goroutine is a lightweight concurrent execution unit in the Go language, which is similar to a coroutine. In order to effectively manage and schedule goroutines, thereby improving the performance and stability of concurrent programs, the Go language provides a rich API.
Create goroutine: Use the go
keyword to create a goroutine, as follows:
go func() { // Goroutine 代码 }
Wait for goroutine to exit: Use WaitGroup
type to wait for all goroutines to exit, as shown below:
var wg sync.WaitGroup wg.Add(numOfWorkers) for i := 0; i < numOfWorkers; i++ { go func(i int) { // Goroutine 代码 wg.Done() }(i) } wg.Wait()
Cancel goroutine: Use context.Context
and context.WithCancel
functions to cancel the execution of goroutine, as shown below:
ctx, cancel := context.WithCancel(context.Background()) go func() { // Goroutine 代码 select { case <-ctx.Done(): return } } // 取消 goroutine cancel()
The scheduler built into the Go language is responsible for managing and scheduling goroutines. It uses the following algorithm to decide when to start a goroutine:
By default, the Go language uses a preemptive scheduling algorithm, but for some scenarios, collaborative scheduling is more appropriate. Cooperative scheduling can be triggered using the runtime.Gosched()
function.
The following is an example of using goroutine to process tasks concurrently:
package main import "fmt" import "sync" func main() { // 创建 goroutine 池 pool := make(chan func()) // 启动 goroutine 池中的 worker for i := 0; i < 10; i++ { go func() { for { // 从池中获取任务 task := <-pool // 执行任务 task() } }() } // 发送任务到池中 for i := 0; i < 100; i++ { pool <- func() { fmt.Println("Task", i) } } // 等待任务完成 var wg sync.WaitGroup wg.Add(100) for i := 0; i < 100; i++ { go func() { defer wg.Done() <-pool }() } wg.Wait() // 关闭池 close(pool) }
The above is the detailed content of Management and scheduling of goroutines in Go concurrent programming. For more information, please follow other related articles on the PHP Chinese website!