Playing with channels
This commit is contained in:
parent
869e00fe38
commit
45239efacc
31
gotime/src/channels.go
Normal file
31
gotime/src/channels.go
Normal file
@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"math"
|
||||
)
|
||||
|
||||
func sum(a []int, c chan int) {
|
||||
sum := 0
|
||||
for _, v := range a {
|
||||
sum += v
|
||||
}
|
||||
to_sleep := time.Duration(100 * math.Abs(float64(sum))) * time.Millisecond
|
||||
fmt.Printf("Sleeping %s...\n", to_sleep)
|
||||
time.Sleep(to_sleep)
|
||||
c <- sum
|
||||
}
|
||||
|
||||
func main() {
|
||||
a := []int{7, 2, 8, -9, 4, 0}
|
||||
|
||||
c := make(chan int)
|
||||
go sum(a[:len(a)/2], c)
|
||||
go sum(a[len(a)/2:], c)
|
||||
x := <-c
|
||||
fmt.Printf("x = %d\n", x)
|
||||
y := <-c
|
||||
fmt.Printf("y = %d\n", y)
|
||||
fmt.Println(x, y, x + y)
|
||||
}
|
Loading…
Reference in New Issue
Block a user