Golang goroutine and channel

/**
  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
		}
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章