Go linux 实践3

Go 的灵魂-goroutine(协程), channel(渠道)

看看吧,不多说了

************************************************

package main

import (
"fmt"
"sync"
"time"
)

func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}

func pt(c chan int) {
t := <-c
fmt.Println("out1:", t)
}

func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
fmt.Println("v=", v)
sum += v
}
c <- sum
}

func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}

func fibonacci1(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}

type SafeCounter struct {
v map[string]int
mux sync.Mutex
}

func (c *SafeCounter) Inc(key string) {
c.mux.Lock()
c.v[key]++
c.mux.Unlock()
}

func (c *SafeCounter) Value(key string) int {
c.mux.Lock()
defer c.mux.Unlock()
return c.v[key]
}

func main() {
go say("World")
say("Hello")

c := make(chan int)
go pt(c)
fmt.Println("in1:", 10)
c <- 10

a := []int{7, 2, 8, -9, 4, 0}
c1 := make(chan int)
go sum(a[:len(a)/2], c1)
go sum(a[len(a)/2:], c1)
x, y := <-c1, <-c1
fmt.Println(x, y, x+y)

ch := make(chan int, 2)
fmt.Println("input 1")
ch <- 1
fmt.Println("input 2")
ch <- 2
fmt.Println(<-ch)
fmt.Println(<-ch)

ch1 := make(chan int, 10)
go fibonacci(cap(ch1), ch1)
for i := range ch1 {
fmt.Println(i)
}

c_11 := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c_11)
}
quit <- 0
}()
fibonacci1(c_11, quit)

tick := time.Tick(100 * time.Millisecond)
boom := time.After(500 * time.Millisecond)
J:
for {
select {
case <-tick:
fmt.Println("tick.")
case <-boom:
fmt.Println("BOOM!")
break J
default:
fmt.Println(" .")
time.Sleep(50 * time.Millisecond)
}
}

sc := SafeCounter{v: make(map[string]int)}
for i := 0; i < 1000; i++ {
go sc.Inc("somekey")
}
ts := time.Second
fmt.Println(ts)
time.Sleep(ts)
var skv int = sc.Value("somekey")
fmt.Println("Inc result:", skv)
fmt.Println("end")
}

原文地址:https://www.cnblogs.com/woodzcl/p/7463772.html