Home  >  Article  >  Backend Development  >  Why does a deadlock occur when the function call that populates the channel is not embedded in a Goroutine?

Why does a deadlock occur when the function call that populates the channel is not embedded in a Goroutine?

王林
王林forward
2024-02-10 12:00:10737browse

当填充通道的函数调用未嵌入 Goroutine 中时,为什么会出现死锁?

When the function call that fills the channel is not embedded in a Goroutine, the reason why a deadlock occurs is because the channel's send and receive operations are blocked. If the function that fills the channel is called in the main Goroutine, and the filling operation is not put into a new Goroutine to run inside the function, then the main Goroutine will wait for the channel to have enough space to receive data, and the filling operation cannot be performed, thus Lead to deadlock. Therefore, in order to avoid deadlock, we need to use Goroutine for concurrent execution in the operation of filling the channel to ensure that the filling operation and the receiving operation can be performed at the same time.

Question content

I'm aware of the sync package and its waitgroup option, I don't want to use it for this test. I'm testing a semaphore.

So I have:

package main

import (
    "fmt"
    "os"
    "time"
)

func main() {

    fmt.print("wassap")

    jobs := make(chan int)
    processstarted := make(chan struct{}, 1)
    processcompleted := make(chan struct{}, 1)

    createjobs(jobs)

    go func() {
        worker(jobs, processstarted, processcompleted)
    }()

    go func() {
        sync(processstarted, processcompleted)
    }()

    time.sleep(3600 * time.second)
    fmt.print("\nend of main...")

    interrupt := make(chan os.signal)
    <-interrupt

}

func createjobs(jobs chan<- int) {
    defer close(jobs)
    for i := 1; i < 20; i++ {
        jobs <- i
    }
}

func worker(jobs <-chan int, processstarted <-chan struct{}, processcompleted <-chan struct{}) {

    for {
        select {
        case i := <-jobs:
            fmt.printf("\nfetching job #%d from channel", i)
            time.sleep(2 * time.second)
        case <-processstarted:
            fmt.print("\nprocess started. waiting for it to be completed")
            <-processcompleted
            fmt.print("\nprocess completed")
        }

    }
}

func sync(processstarted chan<- struct{}, processcompleted chan<- struct{}) {

    // acquire semaphore. send signal to channel to indicate that it is busy
    processstarted <- struct{}{}

    for i := 1; i < 5; i++ {
        fmt.printf("\nprocessing %d", i)
        time.sleep(5 * time.second)
    }

    // release semaphore
    processcompleted <- struct{}{}
}

What I want to test is very simple: I have a createjobs function whose sole purpose is to add an element to a channel, in this case an int channel. Then I have a worker that will pull the object from that channel and sleep for 2 seconds before fetching the next element.

Now, there is also a synchronization function. The only purpose of this function is to simulate a process started when worker is run. If this process is active, it should stop processing the jobs element when sync ends, that's why I have two channels, one means the process started and another means the process ended .

I get the following error when running my code:

fatal error: all goroutines are asleep - deadlock!

If I modify the way createjobs is called, wrap it in a goroutine like this:

go func() {
        createJobs(jobs)
    }()

Then my code runs correctly.

I just want to understand why this is happening. What I mean is: main routine is executing and then it calls createjobs (without newline), so main routine should be blocked until this call ends . Once createjobs ends, there are elements in the channel. main continues execution and starts other goroutines worker and sync to complete their work. Before main ends, I just add a sleeper to give the previously created goroutine time to complete.

I'm not asking for other solutions to this problem, I just want to know what happens when createjobs happens outside of a goroutine.

Workaround

You declare jobs as an unbuffered channel and then try to push 20 values ​​into it synchronously. This will block your main function when you call createjobs(jobs).

Change line 13 to:

    jobs := make(chan int, 20)

...will resolve the deadlock.

Edit - Clarification requested in comments:

Unbuffered channels have no capacity and will block the execution of the producer until the consumer receives the message.

A good analogy for an unbuffered channel is a pipe, in this case the process looks like this:

+------------------+     +------------+      +-------------+
| PRODUCER         |     | PIPE       |      | CONSUMER    |
|                  +---->|            +----->|             |
| createJobs(jobs) |     | unbuffered |      | worker(...) |
|                  |     | channel    |      |             |
+------------------+     +------------+      +-------------+

The deadlock occurs because createjobs(jobs) is called synchronously and no consumer is running yet.

Does it work when the function (producer) is called in a goroutine because basically inserting into the channel and reading from the channel happens in parallel?

Yes. If the producer is called asynchronously, it will not block the main() function, so the consumer will also have a chance to be called. In this case, the producer will push all its tasks one by one, just like the workers consume them one by one.

The above is the detailed content of Why does a deadlock occur when the function call that populates the channel is not embedded in a Goroutine?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete