21

Goroutines and APIs

 4 years ago
source link: https://blog.gnoack.org/post/go-goroutines-and-apis/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Go programming notes

November 18, 2019

Goroutines are a unusual and powerful programming language feature, so they are a tempting toy to play with, and they get a bit overused.

There is some indication that the following Go principle holds true:

Strive to provide synchronous APIs,  let the caller start goroutines.

To put this advice into a more concrete code example:

Do this:

func (t *type) Run(ctx context.Context) {
    // Implementation of background task
}

Instead of this:

func (t *type) Start() {
    t.wg.Add(1)
    go func() {
      // Implementation of background task
      t.wg.Done()
    }
}

func (t *type) Cancel() {
    // Somehow cancel the background task
    t.wg.Wait()
}

Upsides for Run() :

  • The caller gets to decide how the “background” code gets run.
    go
    
  • Background task cancellation is provided through the context.
  • Waiting for the background task has a trivial API (when the function returns), and can be done with the mechanism the caller prefers (waitgroups, channels, …)
  • It’s on the safe side API-wise: There is no Close() method which callers can forget to call (leaking resources).

Another great discussion of this was in the Go Time: On application design podcast (starting around minute 47, Mat Ryer’s explanation really resonated with me)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK