php小編子墨介紹:在Go語言中,select語句是一種非常重要的控制流程語句,它用于同時監聽多個通道的操作,實現并發控制。為什么需要等待select呢?這是因為在并發編程中,我們通常需要同時處理多個通道的數據或事件,而select語句可以幫助我們監聽多個通道,一旦其中任意一個通道可操作,就會執行對應的操作,從而實現并發處理。通過使用select,我們可以有效地避免阻塞,提高程序的響應性和并發能力。
問題內容
我剛剛學習了上下文取消。
這是我的代碼。
package main import ( "fmt" "context" ) func main() { ctx := context.Background() do(ctx) } func do(ctx context.Context) { ctx, ctxCancel := context.WithCancel(ctx) resultCh := make(chan string) go terminate(ctx, resultCh) resultCh <- "value1" resultCh <- "value2" fmt.Println("pre cancel") ctxCancel() fmt.Println("post cancel") } func terminate(ctx context.Context, ch <-chan string) { for { select { case <-ctx.Done(): fmt.Println("terminate") return case result := <-ch: fmt.Println(result) } } }
登錄后復制
想問
為什么會發生這種情況。
我需要什么知識?
我期待輸出。
但得到的實際輸出不包含“終止”。
value1 value2 pre cancel terminate post cancel
登錄后復制
固定代碼
我在取消功能下添加了 time.Sleep 。
那么輸出就是我的預期。
ctxCancel() time.Sleep(100 * time.Millisecond) // add
登錄后復制
解決方法
據我了解,使用 select 背后的核心思想是等待至少一種情況“準備好”。我在下面提供了一個示例,可能會有所幫助。這里 select 用于等待從通道 ch 接收值或發生 1 秒超時。
import ( "fmt" "time" ) func main() { ch := make(chan int) go func() { // Simulate some time-consuming operation time.Sleep(2 * time.Second) ch <- 42 }() select { case result := <-ch: fmt.Println("Received result:", result) case <-time.After(1 * time.Second): fmt.Println("Timeout reached") } }
登錄后復制