Skip to content

Instantly share code, notes, and snippets.

@pravinchandar
Last active July 5, 2022 00:35
Show Gist options
  • Select an option

  • Save pravinchandar/7ad8b1e09a926475a5f07060f42fb76d to your computer and use it in GitHub Desktop.

Select an option

Save pravinchandar/7ad8b1e09a926475a5f07060f42fb76d to your computer and use it in GitHub Desktop.
// Run runs main server loop, it launches the desired count of worker processes
// and also manage them. It listens for requests on the ReqChan. The request is
// then sent to one of the worker processes for processing. The response from
// the worker is then written to the channel supplied by the client via
// ReqChan. It listens for termination signal on the sigChan.
func (p *Process) Run(ctx context.Context, sigChan chan struct{}) {
// Start by signaling to create num workers
createWorker := make(chan struct{})
go func() { createWorker <- struct{}{} }()
// Using hashicorp/go-reap to listen for the worker processes that may have
// died. The pid of the dead worker is sent over deadWorkerNotificatin channel.
deadWorkerNotification := make(reap.PidCh, 1)
stopReap := make(chan struct{}, 1)
go reap.ReapChildren(deadWorkerNotification, nil, stopReap, nil)
for {
select {
case <-createWorker:
// code to spawn desired number of worker processes
case pid := <-deadWorkerNotification:
// code to perform dead worker accounting and also more likely that
// a new worker should be created to replace the dead worker.
// e.g. go func() { createWorker <- struct{}{} }()
case reqChan := <-p.ReqChan:
go func() {
req := <-reqChan
// send the request to one of the jqworker processses for processing
req.Response, req.Error = p.makeRequest(ctx, req.Request)
reqChan <- req
}()
case <-sigChan:
// code to intiate shutdown sequence
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment