Home > Backend Development > Golang > Cooperation between Golang coroutine and channel

Cooperation between Golang coroutine and channel

王林
Release: 2024-04-15 16:57:02
Original
985 people have browsed it

The cooperation of coroutines and Channels can realize concurrent programming and improve program performance and throughput. Through Channels, coroutines can communicate and exchange data safely and efficiently. The main steps are as follows: Create a Channel receiving task. Start multiple coroutines to receive and process tasks from Channel. Create a task on the main thread and send it to the Channel. Closing the Channel tells the coroutine that there are no more tasks. Use sync.WaitGroup to wait for all coroutines to complete.

Golang协程与 channel 的配合

The cooperation between Golang coroutine and Channel

Introduction

Coroutine is a user-mode lightweight thread, which is related to the process or Compared with threads, the creation and destruction of coroutines consumes fewer resources. Channel is a mechanism in the Go language for communication between goroutines. The combination of coroutines and channels enables concurrent programming, thereby improving program performance and throughput.

Practical Case

Let us use a practical case to demonstrate the cooperation between coroutine and channel. This case will show how to process a set of tasks in parallel.

// 任务定义
type Task struct {
    ID   int
    Data []int
}

// 任务处理函数
func processTask(task *Task) {
    // 耗时处理
    fmt.Printf("Processing task %d\n", task.ID)
    time.Sleep(time.Second * 2)
}

func main() {
    // 创建一个 channel 用于接收任务
    tasks := make(chan *Task, 10)

    // 启动 4 个协程来处理任务
    for i := 0; i < 4; i++ {
        go func() {
            for {
                // 从 channel 中接收任务
                task := <-tasks

                // 处理任务
                processTask(task)
            }
        }()
    }

    // 创建任务并将其发送到 channel
    for i := 0; i < 10; i++ {
        task := &Task{
            ID:   i,
            Data: []int{i, i + 1, i + 2},
        }
        tasks <- task
    }

    // 关闭 channel 告知协程没有更多任务
    close(tasks)

    // 等待所有协程完成
    var wg sync.WaitGroup
    wg.Add(4)
    for i := 0; i < 4; i++ {
        go func() {
            // 协程退出时通知WaitGroup
            wg.Done()
        }()
    }
    wg.Wait()
}
Copy after login

Code running process:

  1. Create a channel tasks for receiving tasks.
  2. Start 4 coroutines, each coroutine receives tasks from the channel and processes them.
  3. Create 10 tasks in the main thread and send them to the channel.
  4. Close the channel to inform the coroutine that there are no more tasks.
  5. Use sync.WaitGroup to wait for all coroutines to complete.

Summary

The combination of coroutines and channels can achieve concurrent programming, thereby improving program performance and throughput. By using channels, coroutines can communicate and exchange data safely and efficiently. This is useful for handling large amounts of tasks or scenarios that require parallel processing.

The above is the detailed content of Cooperation between Golang coroutine and channel. 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