The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
xing393939

go 协程和 select 的知识点

  •  
  •   xing393939 ·
    xing393939 · Dec 4, 2020 · 1456 views
    This topic created in 1987 days ago, the information mentioned may be changed or developed.

    无缓存管道和缓存管道

    先看看无缓存管道的例子:

    	a := make(chan bool)
    	go func() {
    		log.Println("goroutine")
    		<-a
    	}()
    	a <- true
    

    这里主协程会等待子协程执行完,但是如果把第一行改成 a := make(chan bool, 1),那么主协程写完消息直接退出了,子协程没有机会执行(只有一个 cpu 时)。但是改成如下子协程又可以执行了:

    	a := make(chan bool, 1)
    	go func() {
    		log.Println("goroutine")
    		<-a
    	}()
    	a <- true
    	a <- true
    

    管道关闭后,select 能一直接受 close 信号

    	a := make(chan bool, 1)
    	go func() {
    		close(a)
    	}()
    	for {
    		select {
    		case _, ok := <-a:
    			log.Println(ok)
    		}
    	}
    

    而用 for range 是不能获取 close 信号的,如下:

    	a := make(chan bool, 1)
    	go func() {
    		a <- true
    		close(a)
    	}()
    	for {
    		for v := range a {
    			log.Println(v)
    		}
    	}
    
    
    1 replies    2020-12-05 00:51:07 +08:00
    9LCRwvU14033RHJo
        1
    9LCRwvU14033RHJo  
       Dec 5, 2020
    range 是循环到 chan 被关闭为止。当然如果一开始就是关闭的,循环就不执行。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   944 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 82ms · UTC 20:07 · PVG 04:07 · LAX 13:07 · JFK 16:07
    ♥ Do have faith in what you're doing.