[Solved] Stop a blocking goroutine [duplicate]


You can’t kill a goroutine from outside – you can’t even reference a specific goroutine; nor can you abort a blocking operation. You can, however, move the for to the outside:

go func() {
   for  {
       select {
       case close := <-closeChan:
          return 0
       case i,ok := <-c:
         // do stuff
         if !ok {
             // channel is closed & empty
             return 0
         }
       }
   }
}()

This will loop forever, and each iteration it will wait for a message on both channels; whichever gets a message first will be processed, then the loop repeats. This is a very common pattern in Go.

5

solved Stop a blocking goroutine [duplicate]