Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang Concurrency
// Concurrency in Go
// ----------------------------------------------------------------
// several processes running at the same time
// dealing with lots of things at once (connections, computations)
// long live Murphy's^H^H^H^H^H^H^HMoore's law!
// Three things: execution, syncing/messaging and control flow
// 1) GOROUTINES
// ----------------------------------------------------------------
// almost like threads but not really, closest ~ is shell's &
// multiplexed over OS threads as necessary
// "500k goroutines simultaneously" - jordan from batch[1]
func main() {
go func() {
time.Sleep(5)
fmt.Println("hi")
}()
}
// 2) CHANNELS
// ----------------------------------------------------------------
// where did my goroutine go?
// send and receive messages with the channel operator <-
c := make(chan int)
go sum(a[:len(a)/2], c) // sum first part of list
go sum(a[len(a)/2:], c) // sum second part of the list
// in sum function
c <- sum // send partial sum to channel c
x,y := <-c, <-c // receive from channel c
fmt.Println(x+y) // print total sum
// can also have buffered channels...
ch := make(chan int, 100)
// ...so when the buffer is full it blocks (throws an exception)
// 3) SELECT
// ----------------------------------------------------------------
// a control structure like if, switch and for
// are my channels ready yet?
// like a switch but...
// "based on ability to communicate rather than equal values" -rob pike
select {
// something to receive from channel c?
case v := <-c:
// channel c is sending v
case <-quit:
// got a quit message
default:
// no channel is ready, do something else to avoid blocking
}
// Bonus: ERROR HANDLING
// ----------------------------------------------------------------
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
@benbrittain
Copy link

benbrittain commented Aug 6, 2012

vad är detta?

@oskarth
Copy link
Author

oskarth commented Aug 7, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment