gpt4 book ai didi

go - 关于goroutine并发的问题

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:59 25 4
gpt4 key购买 nike

我在 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

任何建议或提示都会有所帮助。谢谢。

最佳答案

基本上,您有:

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。然后循环等待,通过 channel 接收 <-cBD , 直到 goroutine 通过 cBD <- data[k] 发送到 channel ,一秒后。例如,

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

关于go - 关于goroutine并发的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com