Go在Windows中如何抢占协程?

huangapple go评论87阅读模式
英文:

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上支持信号抢占非常容易,因为它提供了SuspendThreadGetThreadContext...

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

huangapple
  • 本文由 发表于 2023年1月8日 09:26:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75044949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定