duanqian6295 2017-03-17 08:18
浏览 71
已采纳

goroutine挂起程序中的循环

Why does the following program hang when the time.Sleep(time.Nanosecond) is commented out?

package main

import "fmt"
import "time"
import "sync/atomic"

func main() {
    var ops uint64 = 0
    for i := 0; i < 50; i++ {
        go func() {
            for {
                atomic.AddUint64(&ops, 1)
                time.Sleep(time.Nanosecond)
            }
        }()
    }

    time.Sleep(time.Millisecond)
    opsFinal := atomic.LoadUint64(&ops)
    fmt.Println("ops:", opsFinal)
}

Second question, why does running this program in the sandbox result in "process took too long"?

  • 写回答

1条回答 默认 最新

  • duanla1996 2017-03-17 08:28
    关注

    It's because goroutine is cooperative (not fully preemptive) task, and the context switch only happen when there's some IO, system call, time.Sleep(), or calling large function which have to extend the stack.

    Reference:

    Your atomic.AddUint64(&ops, 1) is small function which does not have to extend stack. so the context switch never occurs.

    Since main thread is also a goroutine, it does not acquire context switch, and sleeps forever.

    There's an open issue to make golang preemptive in tight loop, but not yet solved.

    More useful references:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么实现输入一个要删除的数后删除后显示剩余数再输入再删除显示剩余数(语言-c语言)
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误