Golang中panic: send on closed channel错误的解决方法

Golang中panic: send on closed channel错误的解决方法

package main

import (
	"fmt"
	"math/rand"
	"sync"
)

func drG(wg *sync.WaitGroup, c chan int) func(int, int, int) {

	return func(min, max, itr int) {
		wg.Add(1)
		defer wg.Done()
		for i := 0; i <= itr; i++ {
			c <- rand.Intn(max-min) + max
		}
		close(c)
		wg.Wait()
	}
}

func main() {
	wg := sync.WaitGroup{}
	c1, c2 := make(chan int), make(chan int)
	ar_c1, ar_c2 := []int{}, []int{}

	go drG(&wg, c1)(10, 99, 2)
	go drG(&wg, c1)(111, 999, 3)
	go drG(&wg, c2)(0, 9, 3)
	for i := range c1 {
		ar_c1 = append(ar_c1, i)
	}
	for i := range c2 {
		ar_c2 = append(ar_c2, i)
	}

	fmt.Println(ar_c1, ar_c2)
}

大家好。

我是编程世界的新手,只是把它当作一个爱好。我阅读了关于 goroutine 和 channel 的资料,并想尝试一下,结果遇到了这个挑战。

我遇到了以下错误:

[166 187 121] [15 14 10 17]
panic: send on closed channel

goroutine 7 [running]:
main.main.drG.func2(0x6f, 0x3e7, 0x3)
/tmp/sandbox3358109023/prog.go:17 +0xb5
created by main.main in goroutine 1
/tmp/sandbox3358109023/prog.go:31 +0x19b

Program exited.

当我使用单个 c2 通道的 goroutine 时,它工作正常,没有错误。但在使用具有相同通道的两个 goroutine 时,我遇到了 panic: send on closed channel 错误。

我该如何解决这个问题?如果这对你们来说是一个基础问题,我表示歉意。


更多关于Golang中panic: send on closed channel错误的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中panic: send on closed channel错误的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


import (
	"fmt"
	"math/rand"
	"sync"
)

func drG(wg *sync.WaitGroup, c chan int) func(int, int, int) {

	return func(min, max, itr int) {
		wg.Add(1)
		defer wg.Done()
		for i := 0; i <= itr; i++ {
			c <- rand.Intn(max-min) + max
		}
		close(c)
		wg.Wait()
	}

}

func main() {
	wg := sync.WaitGroup{}
	c1, c2 := make(chan int), make(chan int)
	ar_c1, ar_c2 := []int{}, []int{}

	go drG(&wg, c1)(10, 99, 2)
	go drG(&wg, c1)(111, 999, 3)
	go drG(&wg, c2)(0, 9, 3)
	for i := range c1 {
		ar_c1 = append(ar_c1, i)
	}
	for i := range c2 {
		ar_c2 = append(ar_c2, i)
	}

	fmt.Println(ar_c1, ar_c2)

}

非常感谢您的反馈,我请求您能采纳我的代码并修改它以成功运行。

数组分块和递归这些概念确实很难完全理解。

回到顶部