我遇到了关于goroutine并发的麻烦。在我的预期中,它应该异步运行并几乎同时打印出来,但它真正做的是等待运行
package main
type batchD []string
var cBD = make(chan batchD, 6)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
data := [][]string{}
data = append(data, []string{"71", "40348270", "6", "win888e", "6", "1", "N", "127.0.0.1"})
data = append(data, []string{"71", "40348270", "6", "win888e", "6", "1", "N", "127.0.0.1"})
data = append(data, []string{"71", "40348270", "6", "win888e", "6", "1", "N", "127.0.0.1"})
data = append(data, []string{"71", "129499244", "6", "win888e", "6", "1", "N", "127.0.0.1"})
data = append(data, []string{"71", "40348270", "6", "win888e", "6", "1", "N", "127.0.0.1"})
data = append(data, []string{"71", "40348270", "6", "win888e", "6", "1", "N", "127.0.0.1"})
for k,v := range data {
go func() {
fmt.Println(k,v)
//batchD{}.BatchDeposit(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
delay()
cBD <- data[k]
}()
<-cBD
}
}
func delay() {
time.Sleep(1 * time.Second)
t := Basic.NowTime("Taipei")
fmt.Println(t)
}
0 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
1 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:41
2 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:42
3 [71 129499244 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:43
4 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:44
5 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:45
0 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
1 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
2 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
3 [71 129499244 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
4 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
5 [71 40348270 6 win888e 6 1 N 127.0.0.1]
2017-08-16 12:00:40
任何建议或提示都会有所帮助。感谢。
答案 0 :(得分:2)
基本上,你有:
var cBD = make(chan batchD, 6)
for k := range data {
go func() {
time.Sleep(1 * time.Second)
fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
cBD <- data[k]
}()
<-cBD
}
每个循环都会启动一个goroutine。然后循环通过频道接收<-cBD
等待,直到goroutine一秒钟后通过cBD <- data[k]
发送到频道。例如,
2017-08-16 02:52:46
2017-08-16 02:52:47
2017-08-16 02:52:48
2017-08-16 02:52:49
2017-08-16 02:52:50
2017-08-16 02:52:51