3 回答

TA貢獻1785條經驗 獲得超8個贊
您可以使用上下文來獲取超時和取消,而不需要任何額外的 API。
type runner struct{}
func (r *runner) StartProcessing(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
}
}()
}
這使您可以靈活地設置超時或隨時取消它。您還可以利用現有的上下文,這些上下文可能希望在您不知情的情況下更快地超時或取消。
// normal timeout after 10 seconds
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
run.StartProcessing(ctx)
// decide to cancel early
time.Sleep(3 * time.Second)
cancel()

TA貢獻1780條經驗 獲得超1個贊
你可能會嘗試這樣的事情......你可能不需要原子,但這有效。
package main
import (
"fmt"
"time"
"sync/atomic"
)
var trip = int64(0)
type runner struct{}
func (r *runner) StopProcessing() {
atomic.AddInt64(&trip, 1)
}
func (r *runner) StartProcessing() {
go func() {
for {
if trip > 0 {
break
}
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
}
}()
}
func newRunner() *runner {
return &runner{}
}
func main() {
run := newRunner()
run.StartProcessing()
// now wait 4 seconds and the kill the process
time.Sleep(4 * time.Second)
run.StopProcessing()
}

TA貢獻2016條經驗 獲得超9個贊
通過使用通道來發出何時中斷 goroutine 的信號。您的代碼的相關部分看起來像這樣
type runner struct {
stop chan bool
}
func (r *runner) StopProcessing() {
r.stop <- true
}
func (r *runner) StartProcessing() {
r.stop = make(chan bool)
go func() {
for {
fmt.Println("doing stuff")
time.Sleep(1 * time.Second)
select {
case _ = <-r.stop:
close(r.stop)
return
default:
}
}
}()
}
您可以在此處查看完整示例https://play.golang.org/p/OUn18Cprs0I
- 3 回答
- 0 關注
- 174 瀏覽
添加回答
舉報