2 回答

TA貢獻1884條經(jīng)驗 獲得超4個贊
據(jù)我了解,您愿意限制同時運行的例程數(shù)量并驗證它是否正常工作。我建議編寫一個函數(shù),它將一個例程作為參數(shù)并使用模擬例程來測試它。
在下面的示例中,spawn函數(shù)運行fn例程count次數(shù),但不超過limit例程并發(fā)。我將它包裝到 main 函數(shù)中以在操場上運行它,但您可以對您的測試方法使用相同的方法。
package main
import (
"fmt"
"sync"
"time"
)
func spawn(fn func(), count int, limit int) {
limiter := make(chan bool, limit)
spawned := func() {
defer func() { <-limiter }()
fn()
}
for i := 0; i < count; i++ {
limiter <- true
go spawned()
}
}
func main() {
count := 10
limit := 3
var wg sync.WaitGroup
wg.Add(count)
concurrentCount := 0
failed := false
var mock = func() {
defer func() {
wg.Done()
concurrentCount--
}()
concurrentCount++
if concurrentCount > limit {
failed = true // test could be failed here without waiting all routines finish
}
time.Sleep(100)
}
spawn(mock, count, limit)
wg.Wait()
if failed {
fmt.Println("Test failed")
} else {
fmt.Println("Test passed")
}
}

TA貢獻1842條經(jīng)驗 獲得超13個贊
- 2 回答
- 0 關注
- 268 瀏覽
添加回答
舉報