How to call a goroutine inside of a select case that runs in the scope of the select's parent

Issue

I am building a data tool that collects data in a stream and operates on it. I have a main routine, a “process manager”, which is responsible for creating new routines of an accumulation function. The manager is informed to create the routines based on a channel receive select case which it is running in an infinite for loop (I already have my cancel routine for itself and all of the routines it creates). The problem is that the manager needs to be able to run the goroutine accumulators in its main scope so that they can operate outside of the select and for loop’s scope (I want them to keep running while the manager accepts new cases).

cancel := make(chan struct{})
chanchannel := make(chan chan datatype)

func operationManager (chanchannel chan chan datatype, cancel chan struct{}) {
for {
 select {
  case newchan := <- chanchannel:
    go runAccum(newchan, cancel)
  case <- cancel:
    return
 }
}
}

func runAccum(inchan chan datatype, cancel chan struct{}) {
for {
 select {
  case data := <- inchan;
    //do something
  case <- cancel:
    return
 }
}
}

This is a very, very dumbed-down example of my use-case, but I hope it illustrates my problem’s component pieces. Let me know if this is possible, feasible, reasonable, inadvisable; And no, this is not how I implemented my teardown haha

Solution

There is no “scope” to goroutines. All goroutines are equal.
There is “scope” for closures but your goroutines do not span closures.
So all your goroutines spanned by go runAccum(newchan, cancel) will be like any other goroutine you span, no matter from where.

I assume you did not test your solution?

Answered By – Volker

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.