线和纤维的区别是什么?我听说过来自红宝石的纤维,我也听说过它们在其他语言中也有,有人能简单地给我解释一下线和纤维的区别吗?


当前回答

注意,除了线程和光纤,Windows 7还引入了用户模式调度:

User-mode scheduling (UMS) is a light-weight mechanism that applications can use to schedule their own threads. An application can switch between UMS threads in user mode without involving the system scheduler and regain control of the processor if a UMS thread blocks in the kernel. UMS threads differ from fibers in that each UMS thread has its own thread context instead of sharing the thread context of a single thread. The ability to switch between threads in user mode makes UMS more efficient than thread pools for managing large numbers of short-duration work items that require few system calls.

有关线程、光纤和UMS的更多信息,请参见Dave Probert: Windows 7内部-用户模式调度器(UMS)。

其他回答

线程最初是作为轻量级进程创建的。以类似的方式,纤维是一种轻量级的线程,依靠(简单地说)纤维本身通过提供控制来相互调度。

我猜下一步将是每次你想让他们执行指令时,你都必须向他们发送一个信号(不像我5岁的儿子:-)。在过去(甚至现在在一些嵌入式平台上),所有的线程都是纤维,没有抢占,您必须编写线程以使其表现良好。

在Win32中,光纤是一种用户管理的线程。一个光纤有它自己的堆栈和指令指针等等,但是光纤不是由操作系统调度的:你必须显式地调用SwitchToFiber。相反,线程是由操作系统预先调度的。因此,粗略地说,光纤是在应用程序/运行时级别管理的线程,而不是真正的操作系统线程。

结果是光纤更便宜,应用程序对调度有更多的控制。如果应用程序创建了大量并发任务,并且/或希望在运行时密切优化,这可能很重要。例如,数据库服务器可能选择使用光纤而不是线程。

(同一术语可能有其他用法;如上所述,这是Win32的定义。)

线程由操作系统调度(抢占式)。一个线程可以在任何时候被操作系统停止或恢复,但是纤维或多或少地管理自己(合作)并相互让步。也就是说,程序员控制光纤何时进行处理,以及该处理何时切换到另一条光纤。

线程通常依赖内核来中断线程,以便它或另一个线程可以运行(这被称为抢占式多任务处理),而光纤使用合作多任务处理,在这种情况下,光纤本身放弃了自己的运行时间,以便其他光纤可以运行。

一些有用的链接可能比我解释得更好:

http://en.wikipedia.org/wiki/Fiber_ (computer_science) http://en.wikipedia.org/wiki/Computer_multitasking#Cooperative_multitasking.2Ftime-sharing http://en.wikipedia.org/wiki/Pre-emptive_multitasking

注意,除了线程和光纤,Windows 7还引入了用户模式调度:

User-mode scheduling (UMS) is a light-weight mechanism that applications can use to schedule their own threads. An application can switch between UMS threads in user mode without involving the system scheduler and regain control of the processor if a UMS thread blocks in the kernel. UMS threads differ from fibers in that each UMS thread has its own thread context instead of sharing the thread context of a single thread. The ability to switch between threads in user mode makes UMS more efficient than thread pools for managing large numbers of short-duration work items that require few system calls.

有关线程、光纤和UMS的更多信息,请参见Dave Probert: Windows 7内部-用户模式调度器(UMS)。