不,不可能用纯 Lua 编写抢占式调度程序。在某些时候,抢占式调度程序需要某种机制,例如中断服务例程,以从当前线程中获取控制权并将其交给调度程序,然后调度程序可以将其交给另一个线程。纯 Lua 没有这种机制。
You mention that Windows is written in mostly C/C++. The keyword is mostly. You can't write a preemptive scheduler in pure ANSI C/C++. Usually, part of the interrupt service routine is written in assembly language. Or, the C/C++ compiler implements a non-standard extension that allows interrupt service routines to be written in C/C++. Some compilers allow you to declare a functions with an __interrupt modifier that that causes the compiler to generate a prolong / epilog that allows the function to be used as an interrupt service routine.
Also, code that sets up the interrupt service routine fiddles with CPU registers with memory mapped IO, or a IO instructions. None of this code is portable ANSI C/C++. And, depends on the CPU architecture.