Home > Backend Development > Golang > Goroutine goes to sleep prematurely

Goroutine goes to sleep prematurely

PHPz
Release: 2024-02-09 11:30:31
forward
1145 people have browsed it

Goroutine 过早进入睡眠状态

php editor Banana here introduces a common problem, that is, Goroutine goes to sleep prematurely. Using Goroutine to execute tasks concurrently in the Go language is very efficient, but sometimes we encounter a situation where Goroutine enters the sleep state before executing the task, causing the task to fail to proceed normally. This article will explain the cause of this problem in detail and provide solutions to help everyone better understand and use Goroutine.

Question content

Code:

package main

import (
    "fmt"
    "time"
)

func main() {
    link := make(chan bool)
    stop := make(chan bool)
    go a(link, stop)
    go b(link)
    <-stop
}

func a(link chan bool, stop chan bool) {
    for i := 0; i < 20; i++ {
        time.Sleep(1 * time.Second)
        link <- true
    }
    stop <- true
}

func b(link chan bool) {
    go func() {
        <-link
        fmt.Println("A")
    }()
    go func() {
        <-link
        fmt.Println("B")
    }()
}
Copy after login

This code doesn't do anything special, I just want to understand channels and goroutines. But something went wrong and the coroutine went to sleep after looping twice and the app crashed.

Let's analyze what it does - messages are sent to link every second. Function b receives it in two places, so print a and b are called. So basically every second a and b should appear in the console. But for reasons unknown to me, it doesn't happen, the program prints a and b once and then crashes. I probably don't understand the concept well enough (golang is really not intuitive), so I hope I can get the answer here.

Solution

Sending to an unbuffered channel will only succeed if there is a goroutine receiving data from it. For the first two sends, there are goroutines receiving from the link channel. But they receive a value and terminate, and there are no more goroutines to receive from link, so the third block is sent to link. Since there are no other goroutines running, the program deadlocks.

The above is the detailed content of Goroutine goes to sleep prematurely. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template