####如何判断chan关闭
package main import( "fmt" ) func main(){ c := make(chan bool) close(c) if ok,_ := <-c; ok{ fmt.Println("not closed") }else{ fmt.Println("closed") } }
此方法有个缺点,需要读一下才能判断其有没有被关闭。golang并没有提供一个方法来判断chan是否已经被关闭
####如何用chan做go程同步
package main
####select
select标准指明,select状态块选择一个可读或可写的操作,有点类似epoll。
package main
####超时
chan自身并没有实现超时,只能配合go程和select来模拟超时。当然,目前time库本身已经实现了。
###chan效率
结论
1)> 这里输入引用文本
package main import( "fmt" "time" "sync/atomic" "runtime" ) func main(){ runtime.GOMAXPROCS(4) var producer int64 =0 var consumer int64 = 0 var cc int64 = 0 ctl := make(chan int,100) a := make(chan int,10000) go func(){ var a int64 = 0 var b int64 = 0 var a1 int64 var a2 int64 for{ a1 = atomic.LoadInt64(&producer) a2 = atomic.LoadInt64(&consumer) fmt.Println(a1 - a,a2 - b) a = a1 b = a2 time.Sleep(time.Second) } }() t1 := time.Now() for i:=0;i<10;i++{ go func(){ for j:=0;j<1000000000;j++{ atomic.AddInt64(&producer,1) a <- j+1 } fmt.Println("over") }() } for j:=0;j<10;j++{ go func(v int){ //var b int for{ //select{ //case _ =<-a atomic.AddInt64(&consumer,1) //default: //goto END //} } fmt.Println("over") }(j) } t2 := time.Now() var count int var c int for{ c =<- ctl fmt.Println(c) count = count + 1 if count == 10{ break } } t3 := time.Now() fmt.Println(t2.Sub(t1),t3.Sub(t2),t3.Sub(t1),cc) }
结论,golang的chan实现,每秒钟大概能够生产消费1000万条消息。多个线程情况下,略微少一点。800w左右。性能还是相当强悍的。