goroutine 从具有动态循环的通道读取等待组,在上一个返回之前重用

我正在开发一个小型实用程序,它需要迭代动态范围的项目(可以是 100 或可以是 100000)并将这些项目放入通道中。另一个函数从该通道读取项目并单独对每个项目进行一些处理。我试图用来sync.WaitGroup确保在处理通道中的所有项目之前我的实用程序不会退出。由于我对频道和等待组相当陌生,因此我遇到了错误panic: sync: WaitGroup is reused before previous Wait has returned


https://play.golang.org/p/nMw3END_9qw


package main


import (

    "fmt"

    "github.com/dchest/uniuri"

    "math/rand"

    "sync"

    "time"

)


var wg sync.WaitGroup

var count = 0


func printMe(msg string) {

    time.Sleep(1 * time.Second)

    fmt.Println(count, msg)

}


func makeMePrint(ch chan string) {

    for s := range ch {

        count++

        wg.Add(1)

        printMe(s)

        wg.Done()

    }


}


func writePrint(ch chan<- string) {

    fmt.Println("Starting to insert data in channel")

    for i := 1; i <= rand.Intn(30); i++ {

        s := uniuri.New()

        ch <- s

    }

    fmt.Println("We are done inserting all data in the channel")

    close(ch)

}


func main() {


    var ch = make(chan string)


    go writePrint(ch)

    go makeMePrint(ch)

    time.Sleep(1 * time.Second)

    wg.Wait()

}

这是我正在研究的主要思想(不是确切的代码,而是具有相同数量功能的完全相同的架构)。


如何确保该实用程序仅在通道中的所有项目都是进程时才退出。


任何帮助表示赞赏。


qq_花开花谢_0
浏览 113回答 1
1回答

富国沪深

我终于让它发挥作用了。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "github.com/dchest/uniuri"&nbsp; &nbsp; "math/rand"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")var count = 0func printMe(msg string) {&nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; fmt.Println(count, msg)}func makeMePrint(wg *sync.WaitGroup, ch chan string) {&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; for s := range ch {&nbsp; &nbsp; &nbsp; &nbsp; count++&nbsp; &nbsp; &nbsp; &nbsp; printMe(s)&nbsp; &nbsp; }}func writePrint(wg *sync.WaitGroup, ch chan<- string) {&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; fmt.Println("Starting to insert data in channel")&nbsp; &nbsp; for i := 1; i <= rand.Intn(30); i++ {&nbsp; &nbsp; &nbsp; &nbsp; s := uniuri.New()&nbsp; &nbsp; &nbsp; &nbsp; ch <- s&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("We are done inserting all data in the channel")&nbsp; &nbsp; close(ch)}func main() {&nbsp; &nbsp; wg := &sync.WaitGroup{}&nbsp; &nbsp; var ch = make(chan string)&nbsp; &nbsp; go writePrint(wg, ch)&nbsp; &nbsp; go makeMePrint(wg, ch)&nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; wg.Wait()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go