Home > Backend Development > Golang > Is there a possibility of panic here?

Is there a possibility of panic here?

WBOY
Release: 2024-02-05 21:36:11
forward
1163 people have browsed it

Is there a possibility of panic here?

Question content

func main() {
    rand.Seed(time.Now().Unix())
    ctx, cancelFunc := context.WithCancel(context.Background())
    anies := make(chan any)
    go doSomething(ctx, anies)
    intn := rand.Intn(2)
    if intn == 0 { //BRANCH1
        cancelFunc()
        close(anies) 
    }
    time.Sleep(time.Second)
}

func doSomething(ctx context.Context, anies chan any) {
    for {
         if ctx.Err() == nil { //LINE2
            anies <- 1 //LINE3
        }
    }
}
Copy after login

Is it possible that I will panic when branch1 happens between line2 and line3.


Correct answer


Yes, panic is possible. Below is an example of a timeline where a panic occurs. The rows are arranged in ascending order of time. N: prefix stands for goroutine.

1: Start coroutine 2
2: Call ctx.Err(), it returns nil
1: Call cancelFunc()
1: Close channel anis
2: Send to aniy channel. Panic because the channel is closed.

The above is the detailed content of Is there a possibility of panic here?. 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