我想写个多线程的例子:
有个专门添加字符串到channel的函数 addStr和一个专门打印channel中一个一个字符串的 printStr函数
我想开两个线程专门写,开两个线程专门读,要怎么办?
简单的例子:
package main
import (
"fmt"
"time"
"strconv"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
strCh := make(chan string, 10)
go AddStr(strCh, "polaris")
go AddStr(strCh, "studygolang")
go PrintStr(strCh, 1)
go PrintStr(strCh, 2)
time.Sleep(3e9)
}
func AddStr(ch chan <- string, str string) {
for i := 0; i < 100; i++ {
ch <- str + strconv.Itoa(i)
}
}
func PrintStr(ch <- chan string, i int) {
for {
select {
case str := <- ch:
fmt.Println("i=", i, str)
break
}
}
}
#1