How are user-level threads scheduled/created, and how are kernel level threads created?

后端 未结 3 730
长情又很酷
长情又很酷 2020-12-02 16:13

Apologies if this question is stupid. I tried to find an answer online for quite some time, but couldn\'t and hence I\'m asking here. I am learning threads, and I\'ve been g

3条回答
  •  猫巷女王i
    2020-12-02 16:31

    User level threads are usually coroutines, in one form or another. Switch context between flows of execution in user mode, with no kernel involvement. From kernel POV, is all one thread. What the thread actually does is controlled in the user mode, and the user mode can suspend, switch, resume logical flows of executions (ie. coroutines). It all happens during the quanta scheduled for the actual thread. Kernel can, and will unceremoniously interrupt the actual thread (kernel thread) and give control of the processor to another thread.

    User mode coroutines require cooperative multitasking. User mode threads must periodically relinquish control to other user mode threads (basically the execution changes context to the new user mode thread, without the kernel thread ever noticing anything). Usually what happens is that the code knows a whole lot better when it wants to release control that the kernel would. A poorly coded coroutine can steal control and starve all other coroutines.

    The historical implementation used setcontext but that is now deprecated. Boost.context offers a replacement for it, but is not fully portable:

    Boost.Context is a foundational library that provides a sort of cooperative multitasking on a single thread. By providing an abstraction of the current execution state in the current thread, including the stack (with local variables) and stack pointer, all registers and CPU flags, and the instruction pointer, a execution_context represents a specific point in the application's execution path.

    Not surprisingly, Boost.coroutine is based on Boost.context.

    Windows provided Fibers. .Net runtime has Tasks and async/await.

提交回复
热议问题