测试和学goroutine, 遇到的问题

lccc · · 878 次点击
xmge
欲戴王冠 必承其重
https://github.com/panjf2000/ants
#1
更多评论
改成以下代码后, 可以实现, 但有一个奇怪的问题是select中注释掉time.After和<-t 后就会死锁了, 是什么原因呢? ```go package main import ( "fmt" //"time" ) type Worker struct { Workcount int requestchan chan string workchan chan string } func (w *Worker) Run(strs []string) { for _, v := range strs { go func(s string) { w.requestchan <- s }(v) } for i := 0; i < w.Workcount; i++ { w.worker(i) } //t := time.After(15 * time.Second) for { select { case re := <-w.requestchan: w.submit(re) case work := <-w.workchan: fmt.Println(work) //case <-t: // fmt.Println("---timeout--") // return } } } func (w *Worker) worker(goid int) { go func(id int) { fmt.Printf("goid is %d\n", id) }(goid) } func (w *Worker) submit(s string) { go func() { w.workchan <- s }() } func main() { input := []string{"php", "java", "python", "javascript", "goland", "time", "slice", "reflect", "strings", "regexp", "map", "convert", "google", "complier"} e := Worker{Workcount: 5, requestchan: make(chan string), workchan: make(chan string)} e.Run(input) } ``` fatal error: all goroutines are asleep - deadlock! goroutine 1 [select]: main.(*Worker).Run(0xc00000a080, 0xc00003c6a8, 0xe, 0xe) /home/steven/go/src/mytest/mtest/ch.go:26 +0x18a main.main() /home/steven/go/src/mytest/mtest/ch.go:54 +0xf3 exit status 2
#2
因为你的requestchan workchan 都是非缓冲型的同步chan,主goroutines 同步完全阻塞自然就死锁了。 time.After 相当于存在一个 goroutines,等于并非只有一个 主goroutines,不会产生阻塞死锁自然就没问题了
#3