Table of Contents
Question content
Workaround
Home Backend Development Golang Multiple goroutines reading from the same channel

Multiple goroutines reading from the same channel

Feb 09, 2024 pm 04:30 PM
go language

多个 goroutine 从同一通道读取

#php editor Strawberry will introduce to you the relevant content of multiple goroutines reading from the same channel in this article. In concurrent programming, goroutine is a lightweight thread in the Go language that can perform multiple tasks at the same time. Channels are an important way to communicate between goroutines. When multiple goroutines need to read data from the same channel, we need to pay attention to some issues and take corresponding measures to ensure the correctness and efficiency of the program. In what follows, we’ll explain the process in detail and provide some practical tips and advice.

Question content

Consider spawning multiple goroutines to read values ​​from the same channel. The two workers are generated as expected, but only read one item from the channel and stop reading. I expect the goroutine to continue reading data from the channel until the goroutine sending the value to the channel is closed. Although something is preventing the sender from sending, the goroutine that spawned the project is not closed. Why does each worker only read one value and stop?

The output shows the two values ​​sent, one read by each worker goroutine. The third value is sent but not read from either worker thread.

new worker
new worker
waiting
sending 0
sending 1
sending 2
running func 1
sending value out 1
running func 0
sending value out 0
Copy after login

Go to the amusement park

package main

import (
    "fmt"
    "sync"
)

func workerPool(done <-chan bool, in <-chan int, numberOfWorkers int, fn func(int) int) chan int {
    out := make(chan int)
    var wg sync.WaitGroup

    for i := 0; i < numberOfWorkers; i++ {
        fmt.Println("new worker")
        wg.Add(1)
        // fan out worker goroutines reading from in channel and
        // send output into out channel
        go func() {
            defer wg.Done()
            for {
                select {
                case <-done:
                    fmt.Println("recieved done signal")
                    return
                case data, ok := <-in:
                    if !ok {
                        fmt.Println("no more items")
                        return
                    }
                    // fan-in job execution multiplexing results into the results channel
                    fmt.Println("running func", data)
                    value := fn(data)
                    fmt.Println("sending value out", value)
                    out <- value
                }
            }
        }()
    }

    fmt.Println("waiting")
    wg.Wait()
    fmt.Println("done waiting")
    close(out)
    return out
}

func main() {
    done := make(chan bool)
    defer close(done)

    in := make(chan int)

    go func() {
        for i := 0; i < 10; i++ {
            fmt.Println("sending", i)
            in <- i
        }
        close(in)
    }()

    out := workerPool(done, in, 2, func(i int) int {
        return i
    })

    for {
        select {
        case o, ok := <-out:
            if !ok {
                continue
            }

            fmt.Println("output", o)
        case <-done:
            return
        default:
        }
    }

}
Copy after login

Workaround

The previous comment about the channel not being buffered is correct, but there are other synchronization issues.

Unbuffered channels essentially mean that when a value is written, that value must be received before any other writes can occur.

  1. workerpool Creates an unbuffered channel out to store results, but only returns after all results have been written to out. But since the read from the out channel occurs after out returns, and out is not buffered, workerpool is blocked while trying to write, resulting in death Lock. That's why it looks like each worker is only sending a single value; in fact, after sending the first one, all workers are blocked because nothing can receive the value (you can do this by writing out Move the print statement after to see this)

Fix options include making out have a buffer of size n = number of results (i.e. out := make(chan int, n)) Or make out unbuffered and read from out while writing.

  • done The channel is also not being used correctly. Both main and workerpool rely on it to stop execution, but nothing is written to it! It is also unbuffered and therefore suffers from the deadlock problem mentioned above.
  • To fix this you can first remove the case <-done: from the workerpool and simply scope it by in as it is in Closed in main. done can then be set to a buffered channel to resolve the deadlock.

    Combining these fixes results in:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func workerPool(done chan bool, in <-chan int, numberOfWorkers int, fn func(int) int) chan int {
        out := make(chan int, 100)
        var wg sync.WaitGroup
    
        for i := 0; i < numberOfWorkers; i++ {
            fmt.Println("new worker")
            wg.Add(1)
            // fan out worker goroutines reading from in channel and
            // send output into out channel
            go func() {
                defer wg.Done()
                for data := range in {
                    // fan-in job execution multiplexing results into the results channel
                    fmt.Println("running func", data)
                    value := fn(data)
                    fmt.Println("sending value out", value)
                    out <- value
    
                }
                fmt.Println("no more items")
                return
            }()
        }
    
        fmt.Println("waiting")
        wg.Wait()
        fmt.Println("done waiting")
        close(out)
        done <- true
        close(done)
        return out
    }
    
    func main() {
        done := make(chan bool, 1)
    
        in := make(chan int)
    
        go func() {
            for i := 0; i < 10; i++ {
                fmt.Println("sending", i)
                in <- i
            }
            close(in)
        }()
    
        out := workerPool(done, in, 2, func(i int) int {
            return i
        })
    
        for {
            select {
            case o, ok := <-out:
                if !ok {
                    continue
                }
    
                fmt.Println("output", o)
            case <-done:
                return
            }
        }
    
    }
    Copy after login

    This may solve your problem, but it's not the best way to use channels! The structure itself can be changed simpler without having to rely on buffered channels.

    The above is the detailed content of Multiple goroutines reading from the same channel. 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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    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)

    What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

    Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

    What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

    The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

    How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

    The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

    In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

    The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

    What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

    What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

    What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

    Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

    Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

    Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

    Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

    Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

    See all articles