3 回答

TA貢獻1854條經驗 獲得超8個贊
取消(阻塞)發送
您最初的問題詢問如何取消發送操作。頻道上的發送基本上是“即時的”。如果通道的緩沖區已滿并且沒有準備好的接收器,則通道上的發送會阻塞。
您可以使用select聲明和cancel您關閉的頻道“取消”此發送,例如:
cancel := make(chan struct{})
select {
case ch <- value:
case <- cancel:
}
在另一個 goroutine 上關閉cancel通道close(cancel)將使上面的選擇放棄發送ch(如果它正在阻塞)。
但如前所述,發送在“就緒”通道上是“即時的”,并且發送首先評估要發送的值:
results <- w.Check()
這首先必須運行w.Check(),一旦完成,它的返回值將在 上發送results。
取消函數調用
所以你真正需要的是取消w.Check()方法調用。為此,慣用的方法是傳遞一個context.Context可以取消的值,它w.Check()本身必須監視并“服從”這個取消請求。
請注意,您的函數必須明確支持這一點。沒有函數調用或 goroutines 的隱式終止,請參閱取消 Go 中的阻塞操作。
所以你Check()應該看起來像這樣:
// This Check could be quite time-consuming
func (w *Work) Check(ctx context.Context, workDuration time.Duration) bool {
// Do your thing and monitor the context!
select {
case <-ctx.Done():
return false
case <-time.After(workDuration): // Simulate work
return true
case <-time.After(2500 * time.Millisecond): // Simulate failure after 2.5 sec
return false
}
}
CheckAll()可能看起來像這樣:
func CheckAll(works []*Work) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
num := len(works)
results := make(chan bool, num)
wg := &sync.WaitGroup{}
for i, w := range works {
workDuration := time.Second * time.Duration(i)
wg.Add(1)
go func(w *Work) {
defer wg.Done()
result := w.Check(ctx, workDuration)
// You may check and return if context is cancelled
// so result is surely not sent, I omitted it here.
select {
case results <- result:
case <-ctx.Done():
return
}
}(w)
}
go func() {
wg.Wait()
close(results) // This allows the for range over results to terminate
}()
for result := range results {
fmt.Println("Result:", result)
if !result {
cancel()
break
}
}
}
測試它:
CheckAll(make([]*Work, 10))
輸出(在Go Playground上嘗試):
Result: true
Result: true
Result: true
Result: false
我們true打印了 3 次(工作在 2.5 秒內完成),然后故障模擬開始,返回false并終止所有其他工作。
請注意,sync.WaitGroup上面示例中的 并不是嚴格需要的,因為results它有一個能夠保存所有結果的緩沖區,但總的來說它仍然是一個很好的做法(如果您將來使用較小的緩沖區)。

TA貢獻1772條經驗 獲得超8個贊
簡短的回答是:不。
return
除非 goroutine 本身到達其堆棧的末尾,否則您不能取消或關閉任何 goroutine 。
如果你想取消某些東西,最好的方法是將 a 傳遞給它們并在例程中context.Context
收聽它。context.Done()
每當上下文被取消時,你應該return
在執行 defers(如果有的話)后 goroutine 會自動死掉。

TA貢獻1825條經驗 獲得超4個贊
package main
import "fmt"
type Work struct {
// ...
Name string
IsSuccess chan bool
}
// This Check could be quite time-consuming
func (w *Work) Check() {
// return succeed or not
//...
if len(w.Name) > 0 {
w.IsSuccess <- true
}else{
w.IsSuccess <- false
}
}
//堆排序
func main() {
works := make([]*Work,3)
works[0] = &Work{
Name: "",
IsSuccess: make(chan bool),
}
works[1] = &Work{
Name: "111",
IsSuccess: make(chan bool),
}
works[2] =&Work{
Name: "",
IsSuccess: make(chan bool),
}
for _,w := range works {
go w.Check()
}
for i,w := range works{
select {
case checkResult := <-w.IsSuccess :
fmt.Printf("index %d checkresult %t \n",i,checkResult)
}
}
}
- 3 回答
- 0 關注
- 128 瀏覽
添加回答
舉報