Home > Backend Development > Golang > Management and scheduling of goroutines in Go concurrent programming

Management and scheduling of goroutines in Go concurrent programming

PHPz
Release: 2024-06-04 16:42:00
Original
911 people have browsed it

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.

Management and scheduling of goroutines in Go concurrent programming

Management and Scheduling of Goroutine in Go Concurrent Programming

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.

Goroutine life cycle management

  • Create goroutine: Use the go keyword to create a goroutine, as follows:

    go func() {
    // Goroutine 代码
    }
    Copy after login
  • 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()
    Copy after login
  • 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()
    Copy after login

Goroutine Scheduling

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:

  • Preemptive scheduling: The scheduler can interrupt the running goroutine and switch to another goroutine for execution.
  • Collaborative scheduling: goroutine actively gives up control and hands it to the scheduler to schedule other goroutines.

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.

Practical Case

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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template