V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
dushandz
V2EX  ›  Go 编程语言

求教 Go 里 goroutine 去通道里拿数据 必定后来的先拿走吗?

  •  
  •   dushandz · 2017-11-30 15:51:40 +08:00 · 1366 次点击
    这是一个创建于 2328 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package main
    
    import (
    	"fmt"
    	"math/rand"
    	"sync"
    	"time"
    )
    
    var wg sync.WaitGroup
    
    func init() {
    	rand.Seed(time.Now().UnixNano())
    }
    func main() {
    	court := make(chan int)
    	wg.Add(2)
    	go player("A", court)
    	go player("B", court)
    	court <- 1
    	wg.Wait()
    }
    
    func player(name string, court chan int) {
    	defer wg.Done()
    	for {
    		ball, ok := <-court //走到这里就会阻塞 是吧?
    		if !ok {            //通道关闭
    			fmt.Printf("Player %s Won\n", name)
    			return
    		}
    		n := rand.Intn(100)
    		if n%13 == 0 {
    			fmt.Printf("Player %s missed\n", name)
    			close(court)
    			return
    		}
    		fmt.Printf("Player %s Hit %d \n", name, ball)
    		ball++
    		court <- ball
    
    	}
    }
    
    

    每次打印都是 B 所在的协程先触发

    7 条回复    2017-12-01 10:17:23 +08:00
    araraloren
        1
    araraloren  
       2017-11-30 16:09:04 +08:00   ❤️ 1
    Please search `程序的局部性原理`
    dushandz
        2
    dushandz  
    OP
       2017-11-30 16:16:58 +08:00
    @araraloren ?? 我间隔一段时间 或者 每次跑之前都 clean 还是这样啊
    Micky
        3
    Micky  
       2017-11-30 16:53:01 +08:00
    增加一个协程:
    wg.Add(3)
    go player("A", court)
    go player("B", court)
    go player("C", court)
    执行几次你会发现,有时候是 CBA 的顺序,有时候是 CAB 的顺序
    确实每次都是 C 最先激活,但 B 和 A 的顺序却是随机的
    因此可以推断:并没有固定的 FIFO 或 LIFO 的顺序,但 runtime 在第一次挑选的时候具有某种倾向性
    Micky
        4
    Micky  
       2017-11-30 16:56:23 +08:00   ❤️ 1
    @Micky #3 这个倾向性可能就是 1 楼所说的局部性原理体现吧,不要当做固定特性去 rely on 就行了
    cholerae
        5
    cholerae  
       2017-11-30 17:23:01 +08:00 via Android   ❤️ 1
    纯粹跟 runtime 实现有关,语言上没有做任何保证,不要依赖这个行为。
    per
        6
    per  
       2017-11-30 17:53:02 +08:00   ❤️ 2
    dushandz
        7
    dushandz  
    OP
       2017-12-01 10:17:23 +08:00
    @Micky @per @cholerae @araraloren 多谢大佬们
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   6044 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:19 · PVG 14:19 · LAX 23:19 · JFK 02:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.