Created
September 17, 2012 19:11
-
-
Save 4E71/3739187 to your computer and use it in GitHub Desktop.
GoLang: Concurrency example
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
// Concurrent.go | |
// Simple example that demonstrates usage of Go routines. | |
package main | |
import ( | |
"fmt" | |
"time" | |
"math/rand" | |
) | |
func main() { | |
// zomg. no type declaration. | |
start := time.Now() | |
decoupled_h() | |
elapsed := time.Since(start) | |
fmt.Println(elapsed) | |
} | |
// Demonstrates that although code is synchronous, execution is decoupled. | |
func decoupled_h() { | |
c := fanIn(foo("hello"), foo("world")) | |
for i := 0; i < 20; i++ { | |
fmt.Println(<-c) | |
} | |
} | |
// Demonstrates that the code can run in sync. | |
func sync_h() { | |
h := foo("hello") | |
w := foo("world!") | |
for i := 0; i < 5; i++ { | |
fmt.Printf("f(Goroutine): %q\n", <-h) | |
fmt.Printf("f(Goroutine): %q\n", <-w) | |
} | |
} | |
// Function that prints a string and then sleeps. | |
func foo(msg string) <-chan string { | |
c := make(chan string) | |
go func() { | |
for i := 0; ; i++ { | |
c <- fmt.Sprintf("%s %d", msg, i) | |
// sleep for pseudorandom time | |
time.Sleep(time.Duration(rand.Intn(1337)) * time.Millisecond) | |
} | |
}() | |
return c | |
} | |
// Multiplexing: Takes two channels of input and returns one channel of output | |
func fanIn(input1, input2 <-chan string) <-chan string{ | |
c := make(chan string) | |
go func() { | |
for { | |
select { | |
// select the routine that is "ready" for execution | |
case s:= <- input1: c <- s | |
case s:= <- input2: c <- s | |
} | |
} | |
}() | |
return c | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment