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


当前回答

Win32光纤定义实际上是由太阳微系统公司建立的“绿线”定义。没有必要在某种类型的线程上浪费光纤这个术语,即在用户代码/线程库控制下在用户空间中执行的线程。

为了澄清这一论点,请看以下评论:

使用超线程,多核CPU可以接受多个线程,并将它们分布在每个核上。 超标量流水线CPU接受一个线程执行,并使用指令级并行(ILP)来更快地运行线程。我们可以假设一根线被分解成在平行管道中运行的平行纤维。 SMT CPU可以接受多个线程,并将它们分解成指令纤维,以便在多个管道上并行执行,更有效地使用管道。

我们应该假设进程是由线组成的,而线应该是由纤维组成的。考虑到这个逻辑,将光纤用于其他类型的线程是错误的。

其他回答

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

用最简单的术语来说,线程通常被认为是抢占式的(尽管这可能并不总是正确的,这取决于操作系统),而光纤被认为是轻量级的协作线程。两者都是应用程序的独立执行路径。

With threads: the current execution path may be interrupted or preempted at any time (note: this statement is a generalization and may not always hold true depending on OS/threading package/etc.). This means that for threads, data integrity is a big issue because one thread may be stopped in the middle of updating a chunk of data, leaving the integrity of the data in a bad or incomplete state. This also means that the operating system can take advantage of multiple CPUs and CPU cores by running more than one thread at the same time and leaving it up to the developer to guard data access.

With fibers: the current execution path is only interrupted when the fiber yields execution (same note as above). This means that fibers always start and stop in well-defined places, so data integrity is much less of an issue. Also, because fibers are often managed in the user space, expensive context switches and CPU state changes need not be made, making changing from one fiber to the next extremely efficient. On the other hand, since no two fibers can run at exactly the same time, just using fibers alone will not take advantage of multiple CPUs or multiple CPU cores.

Win32光纤定义实际上是由太阳微系统公司建立的“绿线”定义。没有必要在某种类型的线程上浪费光纤这个术语,即在用户代码/线程库控制下在用户空间中执行的线程。

为了澄清这一论点,请看以下评论:

使用超线程,多核CPU可以接受多个线程,并将它们分布在每个核上。 超标量流水线CPU接受一个线程执行,并使用指令级并行(ILP)来更快地运行线程。我们可以假设一根线被分解成在平行管道中运行的平行纤维。 SMT CPU可以接受多个线程,并将它们分解成指令纤维,以便在多个管道上并行执行,更有效地使用管道。

我们应该假设进程是由线组成的,而线应该是由纤维组成的。考虑到这个逻辑,将光纤用于其他类型的线程是错误的。

在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