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

go 协程和 select 的知识点

  •  
  •   xing393939 ·
    xing393939 · Dec 4, 2020 · 1905 views
    This topic created in 2183 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
    9LCRwvU14033RHJo
    Dec 5, 2020
    1
    range 是循环到 chan 被关闭为止。当然如果一开始就是关闭的,循环就不执行。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4250 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:34 · PVG 17:34 · LAX 01:34 · JFK 04:34
    ♥ Do have faith in what you're doing.