L
L
Leshiy Urban2015-08-23 12:57:50
go
Leshiy Urban, 2015-08-23 12:57:50

What is the correct approach when writing to a private channel in Go?

There are 2 or more data generators writing to a common channel. It is necessary to close the channel on the data consumer side so that the application does not panic.
The simplest option: through panic + recover. But it seems to me that this is conceptually wrong.
Are there standard approaches to solving such a problem?
Example:
Run on playground

package main

import "time"

func generator(v int, ch chan<- int) {
  for {
    ch <- v
  }
}

func main() {
  ch := make(chan int)
  go generator(0, ch)
  go generator(1, ch)
  go generator(2, ch)

  <-ch

  close(ch)
  time.Sleep(1 * time.Second)
  // BOOM!
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2015-08-23
@LeshiyUrban

Create 1 more channel to send the close. In the senders, inside the for , do a select from the close channel with the default branch, where the data is sent.

A
Andrey K, 2015-08-23
@mututunus

There is no way in Go to check the state of a pipe when writing to it. Closing the channel on the recipient side is a rather rare case, most likely the application logic can be redone without it.

O
Oleg Shevelev, 2015-08-26
@mantyr

To "put out" the generator - you need to send him a message "stop working." He will be able to read it between iterations and make a decision "whether to work further" or "not to work further".
To do this, look at the implementation of GetCommand and GetLastCommand in the file https://github.com/mantyr/runner/blob/master/chan.go
This is just one of the implementation options. You can somehow simplify, send not text, but bool, or sometimes instead of the "next" command, reading another channel (for example, time.After()) is used to evenly execute commands in time. An example of using GetCommand is in the Readme https://github.com/mantyr/runner/, GetLastCommand does the same, only skips all available messages and returns only the last one (in other words, it waits for all tasks in the queue to spill out and the channel becomes idle, and only then returns the last value).
You can google on the topic "Golang start stop goroutines"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question