-4

I am trying to create multiple goroutines and keep them running concurrently. Then when a request comes in I want to identify one of them them and stop only that particular goroutine while the rest contiue

File 1

mm := remote_method.NewPlayerCreator()

mm.NewPlayer("Leo", "Messi")

// Lets just assume that the method call starts a bot which starts playing football

mm.NewPlayer("Cristiano", "Ronaldo")

mm.StopPlayer("Leo", "Messi")

File 2

package remote_method

type PlayerCreator struct {
        playerNameChannelNumberMap (map[Player](chan int))
}

type Player struct {
        firstName, lastName string
}

func NewPlayerCreator() DeclaredType {
        var nameChannelMap (map[Player](chan int))
        m := PlayerCreator{nameChannelMap}
        return m
}

func (mm NewPlayerCreator) NewPlayer(firstName string, lastName string) {
     // Update the playerNameChannelNumberMap to add this new Player in the map
     // Since maps are basically called by reference, the map withe the file 1 should be updated or should it ?
     // Call to a goroutine that would create a new player and the player keeps on running in an infinite loop
     // I can add the goroutine code in this method and not create a new method for the goroutine, if it makes more sense like this
}

func (mm NewPlayerCreator) StopPlayer(firstName string, lastName string) {
     // Find the player channel in the map and send a done signal on receiving which it exits
     // Remove the player entry from the map
}

What are the best known practices for doing such a thing ? TIA

The_Lost_Avatar
  • 992
  • 5
  • 15
  • 35

1 Answers1

4

The short answer is "you can't". Goroutines are not like Unix processes or threads; there's no PID or thread ID.

You terminate a goroutine by writing a message to a channel shared between the main routine and the goroutine telling it you want it to go away instead of forcibly terminating it yourself.

I won't reproduce the entire article from https://blog.golang.org/pipelines; you would be better off reading it there. High points:

  • You make it possible to cancel a goroutine by sharing a channel with it (most often named done). The actual type of what you send on this channel is unimportant.
  • When you want to send a "everyone shut down" message, you close the done channel. This causes any read on the channel to immediately succeed with a zero-valued instance of the channel's type, effectively broadcasting a "stop" to every goroutine reading the channel.
  • The goroutines have at their core a select loop, which checks for input available on any input channel and on the done channel. Once the channel is closed, the done channel has input ready, and the goroutine cleans up and exits.

The context type wraps this up and a number of other niceties; reading the https://blog.golang.org/context article will give you more details on using contexts to control goroutines.


Joe McMahon
  • 3,266
  • 21
  • 33