Last active
December 15, 2015 00:59
-
-
Save jahfer/5176870 to your computer and use it in GitHub Desktop.
For blog post: http://blog.jahfer.com/2013/03/16/basic-threading/
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
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
// set up our in/out pipe | |
nums := make(chan int, 3) | |
// anonymous functions! | |
// the 'go' keyword will run this function in a new thread | |
go func() { | |
// lets pause for a millisecond to demo concurrency | |
time.Sleep(1) | |
nums <- 1 | |
}() | |
go func() { | |
nums <- 2 | |
}() | |
go func() { | |
nums <- 3 | |
}() | |
// <-var will block until a value is received | |
x := <-nums | |
y := <-nums | |
z := <-nums | |
// Result depends on which functions finish first | |
fmt.Printf("%d + %d + %d = %d\n", x, y, z, x+y+z) | |
// Usually "2 + 3 + 1 = 6" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment