context
https://pkg.go.dev/context
Last updated
Was this helpful?
https://pkg.go.dev/context
Last updated
Was this helpful?
當我們使用 goroutine 時需要一個地方來儲存互相會共用的變數或是讓 goroutine 在特定情況下停止執行,此時可以使用 context。
包含以下方法
使用前需要把 Background 傳進去
之後放到 WithDeadline 或 WithTimeout 或 WithCancel,最後如果要傳值再放進 WithValue。
在 goroutine 裡面使用 select,當 context timeout 或 cancel 後會觸發 select 裡面的
case <-ctx.Done():
範例:
Use context
to cancel
2. Use a kill channel to signal cancellation and a done channel to indicate that goroutine has been terminated.