【发布时间】:2017-03-12 20:56:13
【问题描述】:
我是 goroutines、channels 等的新手,如果这看起来微不足道,我深表歉意。
我写了以下代码:
for _, h := range hosts {
go func() {
httpClient := cleanhttp.DefaultPooledClient()
// format the URL with the passed host and por
url := fmt.Sprintf("https://%s:%v", h.Name, h.Port)
// create a vault client
client, err := api.NewClient(&api.Config{Address: url, HttpClient: httpClient})
if err != nil {
panic(err)
}
// get the current status
status := v.VaultStatus(client)
// send the status to a channel
s <- strconv.FormatBool(status.Ready)
}()
// assign the value of channel to a var
cs := <-s
// print it
fmt.Printf("Host: %s Status: %s\n", h.Name, cs)
}
},
这个想法很简单,它需要一个主机列表,然后使用 Golang Vault API 去确定当前状态。我很高兴它可以工作。
我想做的是确保这些操作并行发生。当我运行以下代码时,我得到的结果如下:
host: Host1: status: true
host: Host2: status: false
host: Host3: status: true
host: Host4: status: true
这里的问题是这些主机总是以相同的顺序返回。我认为 goroutine 根本不是并行执行的,因为它们似乎一个接一个地运行,然后每次都以相同的顺序打印。
代码是否在做我认为应该做的事情?我如何知道这个 goroutine 是并行运行的?
【问题讨论】: