Home  >  Article  >  Backend Development  >  Why does the provided Go code with WaitGroup and buffered channel result in a deadlock?

Why does the provided Go code with WaitGroup and buffered channel result in a deadlock?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 22:08:02680browse

Why does the provided Go code with WaitGroup and buffered channel result in a deadlock?

Deadlocks in Go with WaitGroup and Buffered Channels

In Go, a deadlock occurs when multiple goroutines are waiting for each other to complete, resulting in a stalemate. This situation can arise when using buffered channels and WaitGroups incorrectly.

Consider the following code:

<code class="go">package main

import "fmt"
import "sync"

func main() {
    ch := make(chan []int, 4)
    var m []int

    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            ch <- m
            return
        }()
    }
    wg.Wait()

    for c := range ch {
        fmt.Printf("c is %v", c)
    }
}</code>

This code is expected to create a channel with a buffer size of 4 and start 5 goroutines, each sending an empty slice to the channel. The main goroutine waits for all goroutines to finish and then ranges over the channel.

However, this code will result in a deadlock. Why?

Cause of the Deadlock:

Two problems exist in the code:

  1. Channel Capacity: The channel has a capacity of 4, which means it can hold up to 4 elements. However, there are 5 goroutines trying to send to the channel, resulting in a situation where the last goroutine will block waiting for a slot to be freed.
  2. Closing the Channel: The range ch loop continues to wait for elements to enter the channel. Since there are no more goroutines left to write to the channel, the loop will wait indefinitely.

Solutions:

  1. Increase Channel Capacity: By increasing the channel capacity to 5, enough slots will be available for all goroutines to send their values without blocking. Additionally, closing the channel after the goroutines have finished writing will signal to the range loop that no more elements are coming, preventing it from waiting indefinitely.

    <code class="go">ch := make(chan []int, 5)
    ...
    wg.Wait()
    close(ch)</code>
  2. Use Done() within the Loop: Instead of closing the channel, one can use the Done() method of WaitGroup to signal when the last goroutine has finished. By calling Done() within the range loop, the main goroutine will be notified when the channel is empty and the loop can exit.

    <code class="go">go func() {
        for c := range ch {
            fmt.Printf("c is %v\n", c)
            wg.Done()
        }
    }()
    wg.Wait()</code>

These solutions resolve the deadlock by ensuring that the channel has sufficient capacity and that the range loop exits when there are no more elements to read from the channel.

The above is the detailed content of Why does the provided Go code with WaitGroup and buffered channel result in a deadlock?. 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