gpt4 book ai didi

multithreading - 为什么 Go 的 LockOSThread 不锁定这个 OS 线程?

转载 作者:IT王子 更新时间:2023-10-29 01:09:03 26 4
gpt4 key购买 nike

The documentation对于 runtime.LockOsThread 状态:

LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.

但是考虑这个程序:

package main

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

func main() {
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
go fmt.Println("This shouldn't run")
time.Sleep(1 * time.Second)
}

main goroutine 连接到由 GOMAXPROCS 设置的一个可用操作系统线程,所以我希望 goroutine 在 main 将不会运行。但是程序打印 This shouldn't run,暂停 1 秒,然后退出。为什么会这样?

最佳答案

来自runtime package documentation :

The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit.

休眠线程不计入 GOMAXPROCS 值 1,因此 Go 可以自由地让另一个线程运行 fmt.Println goroutine。

关于multithreading - 为什么 Go 的 LockOSThread 不锁定这个 OS 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com