Home Backend Development Golang How to implement the producer-consumer pattern using concurrent functions in Go language?

How to implement the producer-consumer pattern using concurrent functions in Go language?

Jul 31, 2023 pm 06:30 PM
function concurrent producer-consumer

How to use concurrent functions in Go language to implement the producer-consumer pattern?

In computer science, the producer-consumer pattern is a classic concurrency design pattern. It involves two main roles: the producer is responsible for generating data, and the consumer is responsible for processing this data. The producer and consumer interact through a shared buffer. The producer puts data into the buffer, and the consumer takes the data out of the buffer for processing.

In the Go language, we can implement the producer-consumer model through concurrent functions and channels. Below is a sample code that demonstrates how to implement this pattern using Go language.

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

// 缓冲区大小
const bufferSize = 5

// 生产者函数
func producer(buffer chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()

    for i := 0; i < 10; i++ {
        value := rand.Intn(100) // 生成一个随机数作为数据
        buffer <- value        // 将数据放入缓冲区
        fmt.Println("Producer produces", value)
        time.Sleep(time.Millisecond * time.Duration(rand.Intn(500)))
    }

    close(buffer) // 关闭缓冲区
}

// 消费者函数
func consumer(buffer <-chan int, wg *sync.WaitGroup) {
    defer wg.Done()

    for value := range buffer {
        fmt.Println("Consumer consumes", value)
        time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
    }
}

func main() {
    buffer := make(chan int, bufferSize)
    var wg sync.WaitGroup

    wg.Add(2)

    go producer(buffer, &wg)
    go consumer(buffer, &wg)

    wg.Wait()
}
Copy after login

In the above code, we define a buffer buffer with a size of 5. Producer function producer Generates random numbers as data and puts them into the buffer. Consumer function consumer takes out data from the buffer and processes it. The main function uses sync.WaitGroup to ensure that the program will not exit until the producer and consumer functions are executed.

By running the above code, we can see that the producer continuously generates data and puts it into the buffer, while the consumer continuously takes data out of the buffer for processing. Since the buffer size is 5, when the buffer is full, the producer will block until there is a free location. Similarly, when the buffer is empty, the consumer will block until data is available.

To summarize, using concurrent functions and channels in the Go language, we can easily implement the producer-consumer model. This model enables producers and consumers to work in a concurrent manner, improving the throughput and responsiveness of the system. By setting the buffer size appropriately, we can control the speed of producers and consumers to adapt to different scenario needs.

The above is the detailed content of How to implement the producer-consumer pattern using concurrent functions in Go language?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

How can concurrency and multithreading of Java functions improve performance? How can concurrency and multithreading of Java functions improve performance? Apr 26, 2024 pm 04:15 PM

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Application of concurrency and coroutines in Golang API design Application of concurrency and coroutines in Golang API design May 07, 2024 pm 06:51 PM

Concurrency and coroutines are used in GoAPI design for: High-performance processing: Processing multiple requests simultaneously to improve performance. Asynchronous processing: Use coroutines to process tasks (such as sending emails) asynchronously, releasing the main thread. Stream processing: Use coroutines to efficiently process data streams (such as database reads).

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

How to use atomic classes in Java function concurrency and multi-threading? How to use atomic classes in Java function concurrency and multi-threading? Apr 28, 2024 pm 04:12 PM

Atomic classes are thread-safe classes in Java that provide uninterruptible operations and are crucial for ensuring data integrity in concurrent environments. Java provides the following atomic classes: AtomicIntegerAtomicLongAtomicReferenceAtomicBoolean These classes provide methods for getting, setting, and comparing values ​​to ensure that the operation is atomic and will not be interrupted by threads. Atomic classes are useful when working with shared data and preventing data corruption, such as maintaining concurrent access to a shared counter.

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

See all articles