32
edits
Changes
Team Go
,no edit summary
== Goroutines ==
A goroutine Goroutine is a function capable of running concurrently with other functions. They're similar to threads except they're much cheaper, light weight and are managed automatically. Goroutines are only a few kilobytes in stack size and their size can grow and shrink whereas thread size needs to be predetermined. Goroutines are multiplexed to fewer OS threads, there may be thousands of goroutines Goroutines on on thread. Goroutines communicate using '''channels'''.
<source lang="go">
package main
import (
"fmt"
"math/rand"
"time"
)
func sayhello(s t chan string, num int) { fmt.Println("Goroutine ", num, " running") time.Sleep(time.Duration(rand.Intn(5)) * time.Second) t <- "Hello!"}func goaway(g chan string, num int) { fmt.Println("Goroutine ", num, " running") time.Sleep(time.Duration(rand.Intn(5)) * time.Second) g <- "go away!"}func main() { t := make(chan string) g := make(chan string)
for i := 0; i < 5; i++ {
}
}
<source>
0
1
2
3
4
Goroutine 4 running
Goroutine 0 running
Goroutine 1 running
Goroutine 2 running
Goroutine 3 running
The Compiler said go away!
</source>
Since the ''go'' keyword is used, the program doesn't wait for each function call to complete before moving on which means the order of the Println statements is scrambled.
== Channels ==
Channels are what Goroutines use to communicate with each other. Channels help Goroutines synchronize their execution. Channels can have directions that restrict them to just sending or receiving. Channels have several characteristics: the type of element you can send through a channel, capacity (or buffer size) and direction of communication specified by a <- operator.