Last active
January 17, 2023 01:12
-
-
Save xsaamiir/7887e3971a0ab948a62deb6c4450eb01 to your computer and use it in GitHub Desktop.
Golang Goroutines cheatsheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from the talk https://www.youtube.com/watch?v=PTE4VJIdHPg | |
// futures | |
future := make(chan int, 1) | |
go func() {future <- process() }() | |
result := <-future | |
// async await | |
c := make(chan int, 1) | |
go func() { c <- process() }() // async | |
v := <-c // await | |
// Scatter/gather | |
type result struct { | |
val int | |
err error | |
} | |
//Scatter | |
c := make(chan result, 10) | |
for i := 0, i < cap(c); i++ { | |
go func() { | |
val, err := process() | |
c <- result{val, err} | |
}() | |
} | |
// Gather | |
var results []int | |
for i := 0; i < cap(c); i++ { | |
res := <-c | |
if res.err != nil { | |
log.Printf("could not process request %d\n", i) | |
continue | |
} | |
results = append(results, res.val) | |
} | |
// Some resources | |
// https://wohldani.com/scatter-gather/ | |
// https://talks.golang.org/2012/concurrency.slide#1 | |
// https://talks.golang.org/2013/advconc.slide#11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment