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

当填充通道的函数调用未嵌入 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. If there is any infringement, please contact admin@php.cn delete
Type Assertions and Type Switches with Go InterfacesType Assertions and Type Switches with Go InterfacesMay 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Using errors.Is and errors.As for Error Inspection in GoUsing errors.Is and errors.As for Error Inspection in GoMay 02, 2025 am 12:11 AM

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

Performance Tuning in Go: Optimizing Your ApplicationsPerformance Tuning in Go: Optimizing Your ApplicationsMay 02, 2025 am 12:06 AM

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement

The Future of Go: Trends and DevelopmentsThe Future of Go: Trends and DevelopmentsMay 02, 2025 am 12:01 AM

Go'sfutureisbrightwithtrendslikeimprovedtooling,generics,cloud-nativeadoption,performanceenhancements,andWebAssemblyintegration,butchallengesincludemaintainingsimplicityandimprovingerrorhandling.

Understanding Goroutines: A Deep Dive into Go's ConcurrencyUnderstanding Goroutines: A Deep Dive into Go's ConcurrencyMay 01, 2025 am 12:18 AM

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

Understanding the init Function in Go: Purpose and UsageUnderstanding the init Function in Go: Purpose and UsageMay 01, 2025 am 12:16 AM

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Understanding Go Interfaces: A Comprehensive GuideUnderstanding Go Interfaces: A Comprehensive GuideMay 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Recovering from Panics in Go: When and How to Use recover()Recovering from Panics in Go: When and How to Use recover()May 01, 2025 am 12:04 AM

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor