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

标签 multithreading go

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/

相关文章:

去风格指南?

c++ - 理解 pthread_cond_wait() 和 pthread_cond_signal()

java - ReentrantLock.Sync 中当前线程变量的搭载是如何工作的?

go - 创建调用图

golang - os.stdout 和 multiwriter 之间的区别

windows - 努力在 Windows 上构建 Gitea

C++优先考虑线程间的数据同步

c# - 哪个异步调用用于数据库连接和仍然响应的 GUI?--

python - 共享内存复杂的可写数据结构

go - 如何在收到参数后安全关闭 golang 服务 - 最佳实践