


Why does a deadlock occur when the function call that populates the channel is not embedded in a 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!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys
