dsbfbz75185 2015-06-27 09:05
浏览 31
已采纳

缓冲的通道工作人员恐慌

I wrote a little worker queue using buffered channels. I want to have the ability to "restart" this worker.

But when I do so I get a panic saying "panic: close of closed channel".

Actually I don't understand why its a closed channel because it shouldn't be closed any more after the make.

Here is the example code (http://play.golang.org/p/nLvNiMaOoA):

package main

import (
    "fmt"
    "time"
)

type T struct {
    ch chan int
}

func (s T) reset() {
    close(s.ch)
    s.ch = make(chan int, 2)
}

func (s T) wrk() {
    for i := range s.ch {
        fmt.Println(i)
    }
    fmt.Println("close")
}

func main() {
    t := T{make(chan int, 2)}
    for {
        go t.wrk()
        time.Sleep(time.Second)
        t.reset()
    }
}

Can you tell me what I'm doing wrong there?

  • 写回答

1条回答 默认 最新

  • douhongxie5436 2015-06-27 09:13
    关注

    The problem is that you have a value receiver in your reset function which means that s will be copied and you don't see the effects on your t variable in the loop.

    To fix that, make it a pointer receiver:

    func (s *T) reset() {
        close(s.ch)
        s.ch = make(chan int, 2)
    }
    

    For more info on this topic see Effective Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100