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

Goroutine goes to sleep prematurely

PHPz
PHPzforward
2024-02-09 11:30:311090browse

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")
    }()
}

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!

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