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 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件