Power priority for go choice

I have the following code snippet:

func sendRegularHeartbeats(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            return
        case <-time.After(1 * time.Second):
            sendHeartbeat()
        }
    }
}

This function is performed in a dedicated routine and sends a heartbeat message every second. The whole process should stop immediately when the context is canceled.

Now consider the following scenario:

ctx, cancel := context.WithCancel(context.Background())
cancel()
go sendRegularHeartbeats(ctx)

This starts a routine with a closed context. In this case, I do not want any heart beat transmitted. Therefore, the first block casein select must be entered immediately.

However, it seems that the order in which the blocks are evaluated caseis not guaranteed, and that the code sometimes sends a beating message, although the context has already been canceled.

What is the correct way to implement this behavior?

"isContextclosed" -check case, .

+6
2

:

, , , sendRegularHeartbeats(), case <-ctx.Done() , , , . case <-time.After(1 * time.Second) 1 , . , , .


case switch ( - , ), - , case select.

Spec: :

, , , . , , . , "select" , .

, . .

, (). select (, ), select, default, , . 2 select, <-ctx.Done(), , .

time.Ticker time.After() (time.After() time.Ticker , , "" ).

:

func sendRegularHeartbeats(ctx context.Context) {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()

    for {
        select {
        case <-ctx.Done():
            return
        default:
        }

        select {
        case <-ctx.Done():
            return
        case <-ticker.C:
            sendHeartbeat()
        }
    }
}

, sendRegularHeartbeats(), / Go Playground.

cancel() 2,5 , 2 :

ctx, cancel := context.WithCancel(context.Background())
go sendRegularHeartbeats(ctx)
time.Sleep(time.Millisecond * 2500)
cancel()
time.Sleep(time.Second * 2)

Go Playground.

+4

, :

  • goroutine
  • goroutines ,
  • , , , , , sendHeartbeat, ,

, , , (, ) , , .

, , , . A select case, . , , ; , select. , , , . , , , .

+3

All Articles