在一个 goroutine 中将项目发送到通道,并在另一个 goroutine 中处理
时间:2024-02-29
浏览:194
作者:佚名
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《在一个 goroutine 中将项目发送到通道,并在另一个 goroutine 中处理》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
对于围棋世界来说真的很陌生,并试图通过实践来学习。我想看看如何使用 go 例程将项目添加到一个 go 例程中的“队列”,而另一个 go 例程监听队列并在它们进入时处理它们。在这种情况下,我有一个函数,它将定义数量的项目添加到 int[] 中,而其他函数则尝试在添加它们时打印它们。我假设需要发送一个标志来表明一个 go 例程已停止添加项目到队列。我对菜鸟问题表示歉意,但我很难理解新的术语和语法。
package main
import "fmt"
func printfromslice(c chan []int){
i := <-c
// wait for item to be added to channel
fmt.print(i)
}
func addtoslice (c chan []int, i int) {
for n := 0; n < i; n++{
c <- n //i know this isnt right
}
// how do we signal this is complete??
}
func main(){
c := make(chan []int)
//add things to []i int
go addtoslice(c, 25)
//do something from []int
go printfromslice(c)
}
**update**
修改为使用以下代码,但现在它只会在关闭之前执行 ~printfromslice` 函数的单个打印表单...
package main
func printFromSlice(c chan int){
i := <-c
// wait for item to be added to channel
println("read")
println(i)
}
func addToSlice (c chan int) {
for n := 0; n < 100; n++{
println("add")
println(n)
c <- n
}
close(c)
}
func main(){
println("starting...")
c := make(chan int)
//add things to []i int
go addToSlice(c)
//do something from []int
go printFromSlice(c)
<-c
}解决方案
你需要添加一个sync.WaitGroup来阻塞主线程,直到两个goroutine完成。您可以参考这个Go by Example。
package main
import "sync"
func printFromSlice(c chan int, wg *sync.WaitGroup) {
defer wg.Done() // Decrement the waitgroup counter by 1 after `printFromSlice` returns
// wait for item to be added to channel
// i := <-c // this only waits / blocks 1 time
// For each message arriving at c, read and print
for i := range c { // this would read all messages until channel is closed
println("read")
println(i)
}
}
func addToSlice(c chan int, wg *sync.WaitGroup) {
defer wg.Done() // Decrement the waitgroup counter by 1 after `addToSlice` returns
for n := 0; n < 100; n++ {
println("add")
println(n)
c <- n
}
close(c)
}
func main() {
var wg sync.WaitGroup
println("starting...")
c := make(chan int)
wg.Add(2) // Adds 2 to the waitgroup counter
//add things to []i int
go addToSlice(c, &wg) // Pass the wait group as reference so they can call wg.Done()
//do something from []int
go printFromSlice(c, &wg) // Pass the wait group as reference so they can call wg.Done()
// <-c // No need for this to block the code
wg.Wait() // Waits / blocks until waitgroup counter is 0
}今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
