GOLANG:学习goroutine让我陷入了僵局

我是 GO 新手,我正试图弄清楚 goroutines 是如何工作的以及如何同步它们。这是我写的一个简单的程序来了解它们:


package main


import (

        "fmt"

        "sync"

        "time"

)


func printAfterDelay(delay time.Duration, message string, wg *sync.WaitGroup) {

        time.Sleep(delay)

        fmt.Println(message)

        wg.Done()

}


func add(a int, b int, chan1 chan int, wg *sync.WaitGroup) {

        c := a + b

        chan1 <- c

        //close(chan1)

        wg.Done()

}


func printer(chan1 chan int, wg *sync.WaitGroup) {

        for result := range chan1 {

                //result := <-chan1

                //time.Sleep(2000 * time.Millisecond)

                fmt.Println(result)

        }

        close(chan1)

        wg.Done()

}


func main() {

        //var wg sync.WaitGroup

        wg := &sync.WaitGroup{}


        fmt.Println("Start...")


        wg.Add(1)

        go printAfterDelay(2000*time.Millisecond, "Try", wg)


        chan1 := make(chan int)

        wg.Add(1)

        go add(5, 4, chan1, wg)


        wg.Add(1)

        go add(3, 1, chan1, wg)


        wg.Add(1)

        go printer(chan1, wg)


        //time.Sleep(3000 * time.Millisecond)

        wg.Wait()


        fmt.Println("End")

}

add 函数接受两个 int,将它们相加并将结果传递给一个 chan。打印机功能从 chan 获取结果并打印它们。这两个函数在 main() 中作为 goroutines 调用,所以我还传递了一个 WaitGroup 作为指针,它在调用 goroutines 之前递增,并在函数结束时递减。


九州编程
浏览 154回答 1
1回答

长风秋雁

以下作品。我的意思是它不会死锁。由于您在通道上的范围循环中具有打印机功能,因此它会在通道关闭后自动停止。我在接近尾声时添加了 3 秒延迟,以便让 try 循环有时间打印。不过请阅读文档。它将 100% 解释这些细节。package mainimport (&nbsp; &nbsp; &nbsp; &nbsp; "fmt"&nbsp; &nbsp; &nbsp; &nbsp; "sync"&nbsp; &nbsp; &nbsp; &nbsp; "time")func printAfterDelay(delay time.Duration, message string, wg *sync.WaitGroup) {&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(delay)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(message)}func add(a int, b int, chan1 chan int, wg *sync.WaitGroup) {&nbsp; &nbsp; &nbsp; &nbsp; c := a + b&nbsp; &nbsp; &nbsp; &nbsp; chan1 <- c&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()}func printer(chan1 chan int, wg *sync.WaitGroup) {&nbsp; &nbsp; &nbsp; &nbsp; for result := range chan1 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(result)&nbsp; &nbsp; &nbsp; &nbsp; }}func main() {&nbsp; &nbsp; &nbsp; &nbsp; //var wg sync.WaitGroup&nbsp; &nbsp; &nbsp; &nbsp; wg := &sync.WaitGroup{}&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Start...")&nbsp; &nbsp; &nbsp; &nbsp; go printAfterDelay(2000*time.Millisecond, "Try", wg)&nbsp; &nbsp; &nbsp; &nbsp; chan1 := make(chan int)&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go add(5, 4, chan1, wg)&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go add(3, 1, chan1, wg)&nbsp; &nbsp; &nbsp; &nbsp; go printer(chan1, wg)&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(3000 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; close(chan1)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("End")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go