第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

測試 Golang Goroutine

測試 Golang Goroutine

Go
www說 2021-09-20 10:46:41
我一直在四處尋找,但到目前為止,只有Ariejan de Vroom在這里寫過類似的文章。我想知道我是否可以將 goroutine 引入單元測試,以便它可以精確計算正在運行的 goroutine 的并發(fā)數(shù)量,并可以告訴我它們是否按照我所說的數(shù)量正確生成了 goroutine。例如,我有以下代碼..import (    "testing"    "github.com/stretchr/testify/assert")func createList(job int, done chan bool) {    time.Sleep(500)    // do something    time.Sleep(500)    done <- true    return}func TestNewList(t *testing.T) {  list := NewList()  if assert.NotNil(t, list) {    const numGoRoutines = 16    jobs := make(chan int, numGoRoutines)    done := make(chan bool, 1)    for j := 1; j <= numGoRoutines; j++ {        jobs <- j        go createList(j, done)        fmt.Println("sent job", j)    }    close(jobs)    fmt.Println("sent all jobs")    <-done}
查看完整描述

2 回答

?
慕村9548890

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")

    }

}


查看完整回答
反對 回復 2021-09-20
?
紅顏莎娜

TA貢獻1842條經(jīng)驗 獲得超13個贊

一種可能的方法是使用runtime.Stack()或分析 的輸出,runtime.debug.PrintStack()以便在給定時間查看所有 goroutine。



查看完整回答
反對 回復 2021-09-20
  • 2 回答
  • 0 關注
  • 268 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號