测试和学goroutine, 遇到的问题

lccc · · 892 次点击
如果requestchan 发送阻塞的goroutine 和 submit函数中 workchan发送阻塞的goroutine 是同一个的话 这个goroutine是不是就deadlock了 ps:我今天才开始看golang,以上就是讨论
#5
更多评论
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