Skip to content

Instantly share code, notes, and snippets.

@bojand
Created September 11, 2018 13:31
Show Gist options
  • Save bojand/62fe55cca75a30ddecbcaf300adde6b2 to your computer and use it in GitHub Desktop.
Save bojand/62fe55cca75a30ddecbcaf300adde6b2 to your computer and use it in GitHub Desktop.
Go concurrent patterns

https://peter.bourgon.org/go-for-industrial-programming/

Futures

future := make(chan int, 1)
go func() { future <- process() }()
result := <- future

Async / await

c := make(chan int, 1)
go func { c <- process() }()  // async
c := <-c                      // await

Scatter-gather

// Scatter
c := make(chan result, 10)
for i := 0; i < cap(c); i++ {
    go func() {
        val, err := process()
        c <- result{val, err}
    }()
}

// Gather
var total int
for i := 0; i < cap(c); i++ {
    res := <-c
    if res.err != nil {
        total += res.val
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment