我是 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
,因此您可能會在一切完成之前收到多條退出消息。
- 1 回答
- 0 關注
- 173 瀏覽
添加回答
舉報
0/150
提交
取消