为什么OS线程被认为很昂贵? [英] Why are OS threads considered expensive?

查看:111
本文介绍了为什么OS线程被认为很昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有许多解决方案旨在实现用户空间"线程.可能是golang.org goroutines,python的绿色线程,C#的异步,erlang的进程等.其想法是即使使用单个或有限数量的线程也允许并发编程.

There are many solutions geared toward implementing "user-space" threads. Be it golang.org goroutines, python's green threads, C#'s async, erlang's processes etc. The idea is to allow concurrent programming even with a single or limited number of threads.

我不明白的是,为什么操作系统线程如此昂贵?如我所见,无论哪种方式,您都必须保存任务堆栈(OS线程或userland线程),该堆栈需要几十KB,并且需要一个调度程序才能在两个任务之间移动.

What I don't understand is, why are the OS threads so expensive? As I see it, either way you have to save the stack of the task (OS thread, or userland thread), which is a few tens of kilobytes, and you need a scheduler to move between two tasks.

操作系统免费提供这两个功能.为什么OS线程应该比绿色"线程更昂贵?由于每个任务"都有专用的操作系统线程,导致性能下降的原因是什么?

The OS provides both of this functions for free. Why should OS threads be more expensive than "green" threads? What's the reason for the assumed performance degradation caused by having a dedicated OS thread for each "task"?

推荐答案

我想修改Tudors的答案,这是一个很好的起点.线程有两个主要的开销:

I want to amend Tudors answer which is a good starting point. There are two main overheads of threads:

  1. 启动和停止它们.涉及创建堆栈和内核对象.涉及内核转换和全局内核锁定.
  2. 保持他们的堆叠状态.

(1)仅在始终创建和停止它们的情况下才是问题.通常使用线程池解决此问题.我认为这个问题实际上是可以解决的.在线程池上调度任务通常不涉及到内核的旅行,这使得它非常快.开销大约是一些互锁的内存操作和一些分配.

(1) is only a problem if you are creating and stopping them all the time. This is solved commonly using thread pools. I consider this problem to be practically solved. Scheduling a task on a thread pool usually does not involve a trip to the kernel which makes it very fast. The overhead is on the order of a few interlocked memory operations and a few allocations.

(2)仅当您有许多个线程(> 100个左右)时,这才很重要.在这种情况下,异步IO是摆脱线程的一种手段.我发现,如果您没有疯狂的线程数量,那么包括阻塞在内的同步IO会比异步IO快一点(您没看错:同步IO更快).

(2) This becomes important only if you have many threads (> 100 or so). In this case async IO is a means to get rid of the threads. I found that if you don't have insane amounts of threads synchronous IO including blocking is slightly faster than async IO (you read that right: sync IO is faster).

这篇关于为什么OS线程被认为很昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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