duanfang5849 2015-06-19 10:31
浏览 61

goroutine的执行时间是几点?

I run the following Go code 10 times:

package main

import (
    "fmt"
    "time"
)

func main() {
    go fmt.Println("Hello")
    fmt.Println("World")
    time.Sleep(1 * time.Millisecond)
}

The output is always "World" first:

World
Hello

Does it manifest the goroutine will execute unitl there is a block in main routine? What is the execution time point of goroutine?

  • 写回答

1条回答 默认 最新

  • douzhi2012 2015-06-19 11:46
    关注

    What is the execution time point of goroutine?

    The compiler will insert yield points into your program at different locations where it seems adequate. For example, in some function calls and seemingly tight loops. Also, a goroutine will yield when blocking on a syscall. So your program will probably yield execution over to the second goroutine when the first goroutine reaches fmt.Println("World") and enters a write syscall. After that non-determinism ensues because we don't know how long this syscall will take.

    This, however, is an implementation detail and you should not be concerned with it. When talking about parallelism, the only timing guarantees (i.e. "happens before") you have are those provided by concurrency primitives like those from the standard library's sync/atomic package.

    TL;DR: Don't rely on yield points for your program to work correctly.

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题