想从一个字符切片[]string中打印切片中的每个元素, 且每个打印动作都用一个goroutine完成, 限制goroutine最大数量 为5。
以下是我写的代码, 但不能打印完整, 5个goroutine用完后不会打切片后面的字符了,怎么让goroutine循环使用, 将其切片中所有的字符 打印完? 哪位高手来指点一下。
```go
package main
import (
"fmt"
"time"
)
type Worker struct {
Workcount int
}
func (w *Worker) Run(ch chan string, strs []string) {
for i := 0; i < w.Workcount; i++ {
var s string
if len(strs) > 0 {
s = strs[0]
strs = strs[1:]
}
createWorker(ch, s, i)
}
}
func createWorker(ch chan string, s string, goid int) {
go func(id int) {
worker(id,ch, s)
}(goid)
}
func worker(id int,ch chan string, str string) {
ch <- str
fmt.Printf("goid is %d , string is %s\n", id, str)
}
func main() {
input := []string{"goland", "time", "slice", "reflect", "strings", "regexp", "map", "convert", "google", "complier"}
e := Worker{Workcount: 5}
ch := make(chan string)
e.Run(ch, input)
t := time.After(5 * time.Second)
for {
select {
case re := <-ch:
fmt.Println(re)
case <-t:
fmt.Println("timeout")
return
}
}
}
```
有疑问加站长微信联系(非本文作者)