简体   繁体   中英

Buffered channel worker panics

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM