线和光纤有什么区别? [英] What is the difference between a thread and a fiber?

查看:99
本文介绍了线和光纤有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线和光纤有什么区别?我听说过红宝石中的纤维,也听说过它们可以用其他语言提供,有人可以简单地向我解释一下线程和纤维之间的区别是什么.

What is the difference between a thread and a fiber? I've heard of fibers from ruby and I've read heard they're available in other languages, could somebody explain to me in simple terms what is the difference between a thread and a fiber.

推荐答案

在最简单的术语中,线程通常被认为是抢占式的(尽管根据操作系统的不同,线程不一定总是如此),而光纤则被认为是抢占式的.轻巧的协作线程.两者都是您的应用程序的单独执行路径.

In the most simple terms, threads are generally considered to be preemptive (although this may not always be true, depending on the operating system) while fibers are considered to be light-weight, cooperative threads. Both are separate execution paths for your application.

对于线程:当前执行路径可随时被中断或抢占(注意:此语句是一种概括,可能并不总是成立,具体取决于OS/线程包/等).这意味着对于线程而言,数据完整性是一个大问题,因为一个线程可能在更新数据块的过程中停止,从而使数据完整性处于不良或不完整状态.这也意味着操作系统可以通过同时运行多个线程并将其留给开发人员来保护数据访问,从而利用多个CPU和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.

使用光纤:仅在光纤产生执行权时中断当前执行路径(与上述相同).这意味着光纤始终在定义明确的位置启动和停止,因此数据完整性不再是问题.另外,由于通常在用户空间中管理光纤,因此无需进行昂贵的上下文切换和CPU状态更改,从而使从一根光纤到另一根光纤的转换极为有效.另一方面,由于没有两个光纤可以完全同时运行,因此仅使用光纤将不会利用多个CPU或多个CPU内核.

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.

这篇关于线和光纤有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆