


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!

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

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.

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

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

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

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

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor
