通过通道和 goroutine 写入切片:为什么切片最终为空

通过通道和 goroutine 写入切片:为什么切片最终为空

php小编鱼仔为您揭示一个关于切片的问题:为什么通过通道和 goroutine 写入切片最终为空?在Go语言中,通道和 goroutine 是并发编程的重要工具,但在某些情况下,使用它们写入切片可能会出现意外结果。本文将详细解释这个问题的原因,并提供解决方案,帮助您更好地理解和处理这种情况。

问题内容

我运行这个函数:

func run() () { // this slice is going to be filled out by a channel and goroutine. vertices := make([]vertex, 0) var wg sync.waitgroup // obtain a writer to fill out the vertices. writer := writer(&wg, vertices) // run an arbitrary logic to send data to writer. logic(writer) // stop the writer reading on the channel. close(writer) // wait for the write to complete. wg.wait() // see if vertices slice is actually filled out. doublecheckvertices(vertices) } 登录后复制