我是 golang 新手,正在研究 goroutine。
我故意编写了使用 goroutine 来除法的简单代码。
首先,我给出基数并继续除它的数,直到它不可整除
但是,我改为go split(n),split(n)它不能像下面那样工作,这是为什么?
■ 源代码
package main
import (
"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 = 0
complete
■ 结果(不工作)
$ go run main.go -n 6
[execute] start
[execute] n = 6, count = 1
[divide] n = 6
叮当猫咪
相关分类