Created
August 4, 2012 20:56
-
-
Save oskarth/3259872 to your computer and use it in GitHub Desktop.
Golang Concurrency
This file contains 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
// 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} | |
} |
liten presentation om concurrency i go bara :p
…On Mon, Aug 6, 2012 at 3:07 PM, Ben Brittain < ***@***.*** > wrote:
vad är detta?
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/3259872
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
vad är detta?