Golang – 如何停止Goroutine
- 使用Channel,通过channel往gouroutine当中传value以叫停
package main
import (
"fmt"
"time"
)
func worker(stopChan chan bool) {
for {
select {
case <-stopChan:
fmt.Println("Stopping worker")
return
default:
fmt.Println("Working...")
time.Sleep(1 * time.Second)
}
}
}
func main() {
stopChan := make(chan bool)
go worker(stopChan)
time.Sleep(5 * time.Second)
stopChan <- true
time.Sleep(1 * time.Second) // Give some time to see the message
}
2. 使用Context
package main
import (
"context"
"fmt"
"time"
)
func worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Stopping worker")
return
default:
fmt.Println("Working...")
time.Sleep(1 * time.Second)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go worker(ctx)
time.Sleep(5 * time.Second)
cancel()
time.Sleep(1 * time.Second) // Give some time to see the message
}
Facebook评论