Home  >  Article  >  Backend Development  >  Golang implements buffer queue

Golang implements buffer queue

WBOY
WBOYOriginal
2023-05-13 10:58:37591browse

The buffer queue is a common data structure that plays an important role in multi-threaded programs. Golang provides built-in channels to implement buffer queues, which can easily implement communication and data transfer between threads. This article will introduce how golang implements buffer queue.

  1. Channel Introduction

Channel is a mechanism used for communication between multiple threads in the golang language. A channel can be thought of as a pipe through which multiple threads can send and receive data. Sending and receiving data in the channel is blocking, which means that if there is no data in the channel or the channel is full, the sender or receiver will be blocked. Channels can be created using the make function, with the following syntax:

make(chan 数据类型, 缓冲区大小)

where the data type is the type of data in the channel, and the buffer size is optional. If the buffer size is not specified, it defaults to 0, which is an unbuffered channel. The syntax for creating an unbuffered channel is as follows:

make(chan 数据类型)
  1. Implementing a buffer queue

In golang, a buffer queue can be implemented through built-in channels. The specific implementation is as follows:

package main

import "fmt"

func main() {
    // 创建缓冲队列
    queue := make(chan int, 10)

    // 发送数据到缓冲队列
    queue <- 1
    queue <- 2
    queue <- 3

    // 从缓冲队列中读取数据
    fmt.Println(<-queue)
    fmt.Println(<-queue)
    fmt.Println(<-queue)
}

The above code creates a channel with a buffer size of 10, sends three integers 1, 2, and 3 to the channel, and reads these three integers from the channel . The syntax for reading data is <-queue, which means reading data from the channel. Note that if the read operation is executed before the send operation, the thread will be blocked.

In addition to the above reading and sending operations, you can also use the len(queue) function to obtain the queue length, which is used to determine whether the queue is full or empty.

  1. Concurrent implementation of the producer-consumer pattern

Buffer queues are usually used to implement the producer-consumer pattern to transfer data between multiple threads. The following is a simple example program that implements one producer and two consumers:

package main

import (
    "fmt"
    "time"
)

func producer(queue chan<- int) {
    // 生产者往队列中写入数据
    for i := 1; i <= 10; i++ {
        queue <- i
        fmt.Printf("生产者写入数据:%d
", i)
        time.Sleep(time.Millisecond * 100)
    }
}

func consumer1(queue <-chan int) {
    // 消费者1从队列中读取数据
    for {
        data := <-queue
        fmt.Printf("消费者1读取数据:%d
", data)
        time.Sleep(time.Millisecond * 200)
    }
}

func consumer2(queue <-chan int) {
    // 消费者2从队列中读取数据
    for {
        data := <-queue
        fmt.Printf("消费者2读取数据:%d
", data)
        time.Sleep(time.Millisecond * 200)
    }
}

func main() {
    // 创建缓冲队列
    queue := make(chan int, 5)

    // 启动生产者协程
    go producer(queue)

    // 启动两个消费者协程
    go consumer1(queue)
    go consumer2(queue)

    // 等待协程执行结束
    time.Sleep(time.Second * 10)
}

The above program creates a channel with a buffer size of 5, starts a producer coroutine and two Consumer coroutine. The producer coroutine writes data to the channel, and the consumer coroutine reads data from the channel. Since the buffer size is 5, the producer can keep writing data to the queue when the queue is not full. The consumer coroutine reads data from the queue every 200 milliseconds and prints it out. After the program ends, the main coroutine waits for all coroutines to finish executing.

  1. Summary

Golang provides built-in channels to implement buffer queues. Communication and data transfer between multiple threads can be achieved through channels, thereby realizing concurrent programming models such as the producer-consumer model. Developers can implement their own concurrent programming solutions based on golang's built-in channels.

The above is the detailed content of Golang implements buffer queue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:golang 1.7 I changedNext article:golang 1.7 I changed