dongtao1262 2018-03-05 03:49
浏览 76

Goroutine执行顺序

I'm a beginner of golang and I'm learning the goroutine and channel. Intuitively, I consider a gorountine in golang is essentially a thread running independently. Therefore, if there are more than one goroutine, the execution order won't be guaranteed. Hence, the following code should output "ping" and "pong" in a random order. However, what I observed is that the program yields "ping" and "pong" in turn. Can anyone explain the reason for me? Any reply would be helpful. Thanks!

Another intriguing observation I found is that if I don't call sleep function inside the printer function, the program will output in a random order.

package main

import (
  "fmt"
  "time"
)

func pinger(c chan string) {
  for i := 0; ; i++ {
    c <- "ping"
  }
}

func printer(c chan string) {
  for {
    msg := <- c
    fmt.Println(msg)
    time.Sleep(time.Second * 1)
  }
}

func ponger(c chan string) {
  for i := 0; ; i++ {
    c <- "pong"
  }
}

func main() {
  var c chan string = make(chan string)

  go pinger(c)
  go ponger(c)
  go printer(c)

  var input string
  fmt.Scanln(&input)
}
  • 写回答

2条回答 默认 最新

  • dongqian9013 2018-03-05 04:36
    关注

    The Go Programming Language Specification

    Channel types

    The capacity, in number of elements, sets the size of the buffer in the channel. If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready.


    You have an unbuffered channel: make(chan string).

    msg := <- c (ready to receive) and c <- "ping" (ready to send): send and receive "ping".

    msg := <- c (ready to receive) and c <- "pong" (ready to send): send and receive "pong".

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)