英文:
How does Go preempt goroutines in windows?
问题
我读到了goroutine现在是可抢占的。抢占是通过一个名为sysmon
的goroutine发送停止信号给已经用完时间片的goroutine来实现的。在posix系统上,我相信这是通过pthread_kill
来完成的。我的问题是:在Windows上如何实现这个功能,因为Windows不支持线程信号?我曾经以为Go运行时可能使用了一个类似pthreads4w
的posix线程库,然而我刚刚看到,即使在pthreads4w
中,pthread_kill
也不支持发送信号。
英文:
I read that goroutines are now preemptible. The preemption is done via a sysmon
goroutine that sends stop signals to goroutines which have used up their time slice. On posix systems, I believe this is done through pthread_kill
. My question is: how does this work in windows since windows doesn't support thread signaling? I had assumed that the go runtime may have been using a posix thread library like pthreads4w
, however I just saw that even in pthreads4w
, pthread_kill
doesn't support sending signals.
答案1
得分: 1
runtime/preempt.go
中的注释概述了运行时中异步抢占的工作原理。特别是与异步抢占相关的部分:
> 在异步安全点进行的抢占是通过使用操作系统机制(例如信号)来暂停线程,并检查其状态以确定goroutine是否在异步安全点。
那么在Windows上如何实现异步抢占呢?正如在原始的提案中提到的非协作式goroutine抢占:
> ### 其他考虑因素
> ... 在Windows上支持信号抢占非常容易,因为它提供了SuspendThread
和GetThreadContext
...
Windows的SuspendThread
函数可以通过线程句柄来暂停线程,GetThreadContext
函数可以获取线程的处理器状态。这些函数的具体用法在runtime/os_windows.go
中实现。
英文:
The comments in runtime/preempt.go
give an overview of how preemption works in the runtime. Specifically to do with asynchronous preemption:
> Preemption at asynchronous safe-points is implemented by suspending the thread using an OS mechanism (e.g., signals) and inspecting its state to determine if the goroutine was at an asynchronous safe-point.
So how does async preemption work on windows? As mentioned in the original proposal for non-cooperative preemption of goroutines:
> ### Other considerations
> ... signaled preemption is quite easy to support in Windows because it provides SuspendThread
and GetThreadContext
...
The Windows SuspendThread
function can be used to suspend a thread by its handle, and GetThreadContext
can be used to get the processor state of the thread. The specific usages of these functions are implemented in runtime/os_windows.go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论