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

Is there a possibility of panic here?

WBOY
WBOYforward
2024-02-05 21:36:111135browse

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
        }
    }
}

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!

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