zoukankan      html  css  js  c++  java
  • Go -- runtime.Gosched()的作用分析

    runtime.Gosched()用于让出CPU时间片。这就像跑接力赛,A跑了一会碰到代码runtime.Gosched()就把接力棒交给B了,A歇着了,B继续跑。
    看代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package main

    import (
        "fmt"
        "runtime"
    )

    func say(s string{
        for i := 0; i 2; i++ {
            runtime.Gosched()
            fmt.Println(s)
        }
    }

    func main({
        go say("world")
        say("hello")
    }

    输出结果:
    hello
    world
    hello
    注意结果:
    1、先输出了hello,后输出了world.
    2、hello输出了2个,world输出了1个(因为第2个hello输出完,主线程就退出了,第2个world没机会了)
    把代码中的runtime.Gosched()注释掉,执行结果是:
    hello
    hello
    因为say(“hello”)这句占用了时间,等它执行完,线程也结束了,say(“world”)就没有机会了。
    这里同时可以看出,go中的goroutins并不是同时在运行。事实上,如果没有在代码中通过
    runtime.GOMAXPROCS(n) 其中n是整数,
    指定使用多核的话,goroutins都是在一个线程里的,它们之间通过不停的让出时间片轮流运行,达到类似同时运行的效果。

    还需要学习一句话:
    当一个goroutine发生阻塞,Go会自动地把与该goroutine处于同一系统线程的其他goroutines转移到另一个系统线程上去,以使这些goroutines不阻塞.

  • 相关阅读:
    iOS.UIKit.13.UITableView -- Simple
    iOS.UIKit.12.UICollectionView
    iOS.UIKit.11.UIPickerView
    iOS.UIKit.10.UIDatePicker
    iOS.UIKit.09.UINavigationBar
    iOS.UIKit.08.UIToolbar
    iOS.UIKit.07.UIAlertView_UIActionSheet
    iOS.UIKit.06.UIProgressView_UIActivityIndicatorView
    iOS.UIKit.05.UIScrollView
    iOS.UIKit.04.UISwitch_UISegmentedControl
  • 原文地址:https://www.cnblogs.com/mafeng/p/6806988.html
Copyright © 2011-2022 走看看