Why Does Passing a WaitGroup Structure by Value Cause a Deadlock in Go Channel Communication?

Patricia Arquette
Release: 2024-10-29 07:47:02
Original
394 people have browsed it

Why Does Passing a WaitGroup Structure by Value Cause a Deadlock in Go Channel Communication?

Deadlock in Go Channel Communication Due to Passing Structure by Value

In your code, you've encountered a deadlock error in your goroutine channel communication. This error is because you're passing a WaitGroup structure by value to your goroutines, which creates a copy of the WaitGroup instead of sharing the original reference.

Why Passing by Value Causes Deadlock

Structures in Go are passed by value, not by reference. When you pass a structure to a function, a copy is created and passed on to the function. This means any changes made to the structure within the function will not be reflected in the original structure outside of the function.

In your case, the goroutines are trying to signal the WaitGroup when they complete their tasks. However, since they're using a copy of the WaitGroup, their Done() calls don't affect the original WaitGroup. As a result, the Wait() call in the main goroutine never completes, leading to a deadlock.

Solution: Passing by Pointer

To resolve this issue, you need to pass the WaitGroup to your goroutines by pointer. This ensures that both the goroutines and the main goroutine share the same reference to the WaitGroup.

Working Example:

Here's a corrected version of your code:

<code class="go">package main

import (
    "fmt"
    "sync"
)

func push(c chan int, wg *sync.WaitGroup) {
    for i := 0; i < 5; i++ {
        c <- i
    }
    wg.Done()
}

func pull(c chan int, wg *sync.WaitGroup) {
    for i := 0; i < 5; i++ {
        result, ok := <-c
        fmt.Println(result, ok)
    }
    wg.Done()
}

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    c := make(chan int)

    go push(c, &wg)
    go pull(c, &wg)

    wg.Wait()
}</code>
Copy after login

Now, when you run this code, you should no longer encounter the deadlock error. The goroutines will successfully signal the WaitGroup, and the main goroutine will be able to complete its execution.

The above is the detailed content of Why Does Passing a WaitGroup Structure by Value Cause a Deadlock in Go Channel Communication?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template