Force priority of go select statement

前端 未结 3 869
你的背包
你的背包 2020-12-14 21:56

I have the following piece of code:

func sendRegularHeartbeats(ctx context.Context) {
    for {
        select {
        case <-ctx.D         


        
3条回答
  •  死守一世寂寞
    2020-12-14 22:27

    If it is absolutely critical to maintain that priority of operations, you can:

    • Consume from each channel in a separate goroutine
    • Have each of those goroutines write a message to a shared third channel indicating its type
    • Have a third goroutine consume from that channel, reading the messages it receives to determine if it is a tick and should sendHeartbeat or if it is a cancel and it should exit

    This way, messages received on the other channels will (probably - you can't guarantee order of execution of concurrent routines) come in on the third channel in the order they're triggered, allowing you to handle them appropriately.

    However, it's worth noting that this is probably not necessary. A select does not guarantee which case will execute if multiple cases succeed simultaneously. That is probably a rare event; the cancel and ticker would both have to fire before either was handled by the select. The vast majority of the time, only one or the other will fire at any given loop iteration, so it will behave exactly as expected. If you can tolerate rare occurrences of firing one additional heartbeat after a cancellation, you're better off keeping the code you have, as it is more efficient and more readable.

提交回复
热议问题