如何保证通过通道生产和消费数据是安全的
how to make it be safe for produce and consume data by channel
我是 golang 的新手,这是我的目的,我想获得 2 个例程 运行ning 与一个公共通道并发,消费者应该在通道创建后启动,并始终获取数据直到通道关闭,我的代码模板如下:
var userChannel chan string
for index := 0; index < *clientNums; index++ {
wg.Add(1)
go run1()
go run2()
}
wg.Wait()
}
func run1() {
defer wg.Done()
// ...some logic
userChannel = make(chan string, *readUserNums)
for index := 0; index < *readUserNums; index++ {
//...some logic
userChannel <- userId
//...some logic
}
close(userChannel)
}
func run2() {
for sendId := range userChannel {
//...some logic
}
}
在我的代码中,如果首先 run2
运行 它将出现恐慌,因为尚未创建通道并且通道中没有数据。我怎样才能达到我的目的?谢谢
先创建通道,然后将其传递到您的 goroutine 中,而不是将其存储在全局中并动态创建。
即使最初 userChannel
上没有数据,只要创建了 userChannel
就不会成为问题,这里失败是因为没有创建通道。
最好在调用 run1
或 run2
之前创建频道并传递频道。
仅供参考:如果通道是由通道创建的,如果通道上没有数据,并且如果我们尝试从通道读取数据,这将是一个阻塞调用,并将等待直到数据被接收到等待通道中。
我是 golang 的新手,这是我的目的,我想获得 2 个例程 运行ning 与一个公共通道并发,消费者应该在通道创建后启动,并始终获取数据直到通道关闭,我的代码模板如下:
var userChannel chan string
for index := 0; index < *clientNums; index++ {
wg.Add(1)
go run1()
go run2()
}
wg.Wait()
}
func run1() {
defer wg.Done()
// ...some logic
userChannel = make(chan string, *readUserNums)
for index := 0; index < *readUserNums; index++ {
//...some logic
userChannel <- userId
//...some logic
}
close(userChannel)
}
func run2() {
for sendId := range userChannel {
//...some logic
}
}
在我的代码中,如果首先 run2
运行 它将出现恐慌,因为尚未创建通道并且通道中没有数据。我怎样才能达到我的目的?谢谢
先创建通道,然后将其传递到您的 goroutine 中,而不是将其存储在全局中并动态创建。
即使最初 userChannel
上没有数据,只要创建了 userChannel
就不会成为问题,这里失败是因为没有创建通道。
最好在调用 run1
或 run2
之前创建频道并传递频道。
仅供参考:如果通道是由通道创建的,如果通道上没有数据,并且如果我们尝试从通道读取数据,这将是一个阻塞调用,并将等待直到数据被接收到等待通道中。