英文:
Loop values for one go channel to other
问题
请问有人可以帮我检查一下我的代码,看看为什么会出现死锁的情况吗?
package main
import (
"fmt"
"sync"
)
func main() {
myCh := make(chan int, 10)
wg := &sync.WaitGroup{}
wg.Add(10)
// 只读通道
go func(ch <-chan int, wg *sync.WaitGroup) {
value := <-myCh
fmt.Println(value)
wg.Done()
}(myCh, wg)
// 只写通道
go func(ch chan<- int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
myCh <- i
}
wg.Done()
}(myCh, wg)
wg.Wait()
}
我想从发送通道发送循环值,而其他通道只接收每次迭代的值。
英文:
Could anyone please review my code and can check why I am facing a deadlock?
package main
import (
"fmt"
"sync"
)
func main() {
myCh := make(chan int, 10)
wg := &sync.WaitGroup{}
wg.Add(10)
// READ ONLY
go func(ch <-chan int, wg *sync.WaitGroup) {
value := <-myCh
fmt.Println(value)
wg.Done()
}(myCh, wg)
// send ONLY
go func(ch chan<- int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
myCh <- i
}
wg.Done()
}(myCh, wg)
wg.Wait()
}
I want to send the loop values from SEND CHANNEL and OTHER CHANNEL should only recieve the values of each iteration.
答案1
得分: 2
你的读取器go例程在接收到第一个数据后就退出了。你需要在其中加入一个for循环来持续读取该通道。
其次,在外部循环中,你不需要调用wg.Sync(),因为它也会减少等待组。
package main
import (
"fmt"
"sync"
)
func main() {
myCh := make(chan int, 10)
wg := &sync.WaitGroup{}
wg.Add(10)
// 只读
go func(ch <-chan int, wg *sync.WaitGroup) {
for value := range myCh { // 这个循环将持续读取通道
fmt.Println(value)
wg.Done()
}
}(myCh, wg)
// 只发送
go func(ch chan<- int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
myCh <- i
}
// wg.Done() <- 这里不需要
}(myCh, wg)
wg.Wait()
fmt.Println("DONE")
}
希望对你有帮助!
英文:
Your reader go routine exits after the FIRST received data. You have to include a for loop into it to continously read that channel.
Secondly you don't need to call wg.Sync() in your outer loop, because it also decreases the waitgroup.
package main
import (
"fmt"
"sync"
)
func main() {
myCh := make(chan int, 10)
wg := &sync.WaitGroup{}
wg.Add(10)
// READ ONLY
go func(ch <-chan int, wg *sync.WaitGroup) {
for value := range myCh { // this loop will read the channel continously
fmt.Println(value)
wg.Done()
}
}(myCh, wg)
// send ONLY
go func(ch chan<- int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
myCh <- i
}
// wg.Done() <- This not needed here
}(myCh, wg)
wg.Wait()
fmt.Println("DONE")
}
答案2
得分: 1
你在wg.Add(10)
中添加了delta = 10,并且只调用了两次wg.Done()。
你应该要么调用wg.Add(2)
,要么调用wg.Done()
十次。
现在主函数在wg.Wait()
处被锁住,等待另外八次wg.Done()
的调用。
英文:
You are adding delta = 10 in wg.Add(10)
, and call wg.Done() only twice.
You should either call wg.Add(2)
or call wg.Done()
ten times.
Right now the main function locks at wg.Wait()
and waits for eight more wg.Done()
calls.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论