/**
golang goroutine and channel
*/
package main
import (
"fmt"
_ "io"
_ "os"
_ "reflect"
"runtime"
_ "runtime/pprof"
"time"
)
var p = fmt.Println
func test(p string) {
for i := 0; i < 3; i++ {
time.Sleep(200 * time.Millisecond)
fmt.Println("----------go ", p, "---------------")
}
}
//-----------------------------------
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
go test("test1")
go test("test2")
time.Sleep(2 * time.Second)
//----------channel-------------
ch := make(chan bool, 2)
ch <- true
ch <- true
close(ch)
p(len(ch), cap(ch))
for i := 0; i < cap(ch)+1; i++ {
v, ok := <-ch
p(v, ok)
}
p("----------------------------------------------------")
c := make(chan string)
go func(c chan string) {
for {
select {
case v, b := <-c:
p(v, b)
}
time.Sleep(100 * time.Millisecond)
}
}(c)
for {
var input string
fmt.Scanln(&input)
c <- input
if input == "exit" || input == "quit" {
break
}
}
}
Golang goroutine and channel
最新推荐文章于 2022-04-14 17:31:27 发布