golang的goroutine与线程?

刚接触协程不久,看到golang的goroutine模式

  • goroutine可以在不同线程中并行运行

  • 在goroutine中共享资源必须加锁

  • 可以配置调度goroutine的线程数量(GOMAXPROCS)

问题

  1. 什么时候goroutine会被不同的线程调度?

  2. 当把GOMAXPROCS配置为1时,所有goroutine都在单线程中跑,是不是就不用加锁了(像lua一样)

阅读 4.5k
2 个回答

1.比如你这个goroutine A执行IO操作导致goroutine切换,而新上来的goroutine B执行了os.Stdin.Read这样的导致线程彻底阻塞的操作,这个时候goroutine A在执行完IO操作进入就绪状态后就会切换到另一个线程执行。
2.不是,尽管你现在可能会发现多个goroutine不加锁执行偶尔会报纸相同的结果,但Go的设计并不保证goroutine执行调度的顺序安全,比如这段代码。

package main

import (
    "fmt"
    "runtime"
    "time"
)



func main(){
    runtime.GOMAXPROCS(1)

    t := 0

    go func() {
        for i := 0; i < 10000; i++ {
            // Some computation prior to using t.Num
            time.Sleep(300 * time.Microsecond)
            num := t
            // Some computation using num
            time.Sleep(100 * time.Microsecond)
            t = num + 1
        }
    }()

    go func() {
        for i := 0; i < 10000; i++ {
            num := t
            // Some computation using num
            time.Sleep(300 * time.Microsecond)
            t = num + 1
        }
    }()

    go func() {
        for i := 0; i < 10000; i++ {
            num := t
            // Some computation using num
            time.Sleep(200 * time.Microsecond)
            t = num + 1
        }
    }()

    time.Sleep(3 * time.Second) // Wait goroutines to finish

    fmt.Println(t)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题