亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

關于goroutine中goroutine的行為

關于goroutine中goroutine的行為

Go
臨摹微笑 2023-07-26 19:54:43
我是 golang 新手,正在研究 goroutine。我故意編寫了使用 goroutine 來除法的簡單代碼。首先,我給出基數并繼續除它的數,直到它不可整除但是,我改為go split(n),split(n)它不能像下面那樣工作,這是為什么?■ 源代碼package mainimport (    "flag"    "fmt"    "log"    "net/http"    "os"    "strconv")var next = make(chan int)var quit = make(chan int)func divide(n int) {    defer func(){ quit <- 1 }()    fmt.Println("[divide] n = " + strconv.Itoa(n))    r := n % 2    if r == 0 {        next <- n / 2    }}func execute() {    fmt.Println("[execute] start")    count := 0    end   := false    for !end {        select {        case n := <- next:            count++            fmt.Println("[execute] n = " + strconv.Itoa(n) + ", count = " + strconv.Itoa(count))            go divide(n)        case _ = <- quit:            count--            fmt.Println("[execute] end. count = " + strconv.Itoa(count))            if count <= 0 {                end = true            }        }    }    fmt.Println("complete")    os.Exit(0)}func main() {    base := flag.Int("n", 1, "Input the number")    flag.Parse()    if *base <= 0 {        fmt.Println("please more than 1")        os.Exit(0)    }    go execute()    next <- *base    if err := http.ListenAndServe(":8080", nil); err != nil {        log.Fatal("ListenAndSearver:", err)    }}■ 結果(工作正常)$ go run main.go -n 6[execute] start[execute] n = 6, count = 1[divide] n = 6[execute] n = 3, count = 2[execute] end. count = 1[divide] n = 3[execute] end. count = 0complete■ 結果(不工作)$ go run main.go -n 6[execute] start[execute] n = 6, count = 1[divide] n = 6
查看完整描述

1 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

沒有go divide()內部執行:

  • execute() 從next通道讀取,調用divide

  • 除法()等待寫入next

  • execute()仍在等待divide()返回,因此程序現在陷入僵局。

go divide()內部執行:

  • execute() 從next通道讀取數據,divide在新的 goroutine 中啟動,繼續等待

  • 除法()寫入next

  • execute() 從 讀取next,啟動另一個 goroutine 等。

請注意,一旦divide寫入next,它就會繼續寫入quit,因此您可能會在一切完成之前收到多條退出消息。


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號