猿问

为什么不执行我所有的戈鲁丁?需要解释

 func main() {

    var wg sync.WaitGroup

    ch := make(chan int,5)

    start:= time.Now()

    cnt:=0

    wg.Add(10000)

    for i:=0; i<10000; i++ {

        ch <- 1

        go func() {

            defer wg.Done()

            doSomething()

            cnt++

            <-ch

        }()

    }

    wg.Wait()

    fmt.Println(cnt)

    end:= time.Now()

    fmt.Println("End of program.",end.Sub(start))

}


在这里,我想同时执行程序,并且我还希望最多有5个goroutines。问题是当我打印出“cnt”时,它不会是10000。这意味着我有一些没有被执行的goroutines。如何解决此问题?


现在我正在使用互斥体来解决这个问题,但是这个程序的运行时不会更好,我不明白为什么。


    func main() {

    var wg sync.WaitGroup

    var mutex sync.Mutex

    ch := make(chan int,5)

    start:= time.Now()

    cnt:=0

    for i:=0; i<10000; i++ {

        wg.Add(1)

        ch <- 1

        go func() {

            defer wg.Done()

            defer mutex.Unlock()

            mutex.Lock()

            doSomething()

            cnt++

            <-ch

        }()

    }

    wg.Wait()

    fmt.Println(cnt)

    end:= time.Now()

    fmt.Println("End of program.",end.Sub(start))

}


芜湖不芜
浏览 73回答 1
1回答

繁华开满天机

尝试使用以下程序中的工人数量,看看哪个数字能给你最好的结果。虽然,你进行基准测试的方式并不是很可靠,通常应该避免。但是这个程序应该更好地工作;肯定有更好的实现。所以在这里,你只是生成了大量的goroutines,但在你的情况下,这是goroutines,这真的没有必要,对于小案例;这是一个过度的。workers10000注意:对我来说,这个程序的工作原理比你拥有的实现好>50%。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")type work struct {&nbsp; &nbsp; wg&nbsp; &nbsp;*sync.WaitGroup&nbsp; &nbsp; jobs <-chan struct{}&nbsp; &nbsp; mu&nbsp; *sync.Mutex&nbsp; &nbsp; val *int}// worker is responsible for executing the work assignedfunc worker(w work) {&nbsp; &nbsp; for range w.jobs {&nbsp; &nbsp; &nbsp; &nbsp; w.mu.Lock()&nbsp; &nbsp; &nbsp; &nbsp; *w.val++&nbsp; &nbsp; &nbsp; &nbsp; w.mu.Unlock()&nbsp; &nbsp; }&nbsp; &nbsp; w.wg.Done()}func main() {&nbsp; &nbsp; start := time.Now()&nbsp; &nbsp; jobs := make(chan struct{}, 2) // Number of jobs (buffer)&nbsp; &nbsp; workers := 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Number of workers&nbsp; &nbsp; cnt := 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Shared variable among workers&nbsp; &nbsp; work := work{&nbsp; &nbsp; &nbsp; &nbsp; wg:&nbsp; &nbsp;&sync.WaitGroup{},&nbsp; &nbsp; &nbsp; &nbsp; jobs: jobs,&nbsp; &nbsp; &nbsp; &nbsp; mu:&nbsp; &nbsp;&sync.Mutex{},&nbsp; &nbsp; &nbsp; &nbsp; val:&nbsp; &cnt,&nbsp; &nbsp; }&nbsp; &nbsp; // Worker Pool&nbsp; &nbsp; work.wg.Add(workers)&nbsp; &nbsp; for i := 0; i < workers; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go worker(work)&nbsp; &nbsp; }&nbsp; &nbsp; // Allocate jobs (Signal worker(s))&nbsp; &nbsp; for i := 0; i < 10000; i++ {&nbsp; &nbsp; &nbsp; &nbsp; jobs <- struct{}{}&nbsp; &nbsp; }&nbsp; &nbsp; // Ask the workers to stop&nbsp; &nbsp; close(jobs)&nbsp; &nbsp; work.wg.Wait()&nbsp; &nbsp; fmt.Println(cnt)&nbsp; &nbsp; fmt.Println("End of program: ", time.Since(start))}
随时随地看视频慕课网APP

相关分类

Go
我要回答