O
O
oke11o2016-05-22 15:20:06
go
oke11o, 2016-05-22 15:20:06

How to inform structurs about an error in one of them?

I have 8 goroutines, each of which creates a structure with a connection.
If one connection encounters an unexpected error, I need to close that connection and tell the rest of the similar structures to close as well.
How to do it?
I got this solution. But she seems bulky.

// Publish is method for use in goroutines
func Publish(in <-chan []byte, goroutines int, config Config) {
    
    done := make(chan bool, goroutines - 1)
    stop := make(chan bool, goroutines - 1)
    defer func () {
        close(done)
        close(done)
    } ()
    
    var wg sync.WaitGroup
    for i := 0; i < goroutines; i++ {
        wg.Add(1)
        go func(wg *sync.WaitGroup, in <-chan []byte, stop, done chan bool, config Config) {
            defer wg.Done()
            
            var conn connect
            conn.Init(config)
            conn.setDone(done)
            conn.setStop(stop)
            defer conn.close()
            
            for body := range in {
                conn.publishMessage(body)
            }
            
        } (&wg, in, stop, done, config)
    }
    go func (goroutines int, done <-chan bool, stop chan<- bool) {
        select {
        case <- done:
            for i := 0; i < goroutines - 1; i++ {
                stop <- true
            } 
        }
        
    } (goroutines, done, stop)
    wg.Wait()
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2016-05-22
@oke11o

So this is one of the first things you need to know with competitive code, use the context:
for example, native - https://godoc.org/golang.org/x/net/context
Or there are other implementations, but you still need to understand them, the standard one is simpler .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question