3 ms·
I'm going to call them "green threads" in this context, don't read into it because the terminology is loose. - Since GT are known to a compiler/runtime they ca
by duped 4y ago
I'm going to call them "green threads" in this context, don't read into it because the terminology is loose.
- Since GT are known to a compiler/runtime they can be cooperative, as opposed to preemptive. OS threads cannot introspect into what your code is doing. That means GT may insert suspend and resume points at API boundaries, for example at any kind of IO. While an OS could implement this in theory (switch threads at i/o syscalls) in practice I don't think there are any thread schedulers that do this.
- GT have orders of magnitude faster context switches than OS threads. All they need to do is swap a stack frame pointer.
- GT often have growable stacks that start extremely small, OS threads have larger default stack sizes that don't grow. This makes starting and destroying GT cheaper, and they can use less memory than the equivalent number of OS threads.
As for why OS threads don't just work the same, there are some disadvantages. You can't pin a GT to a single core, or set thread affinity. Context switching an OS thread is more expensive because it's doing more things, like saving the signal mask (which invokes a syscall, hence the cost). The large fixed stack size means that they don't have to perform memory allocation on a function call once the stack is too small. They have to be preemptive since the OS doesn't know anything about what the program is doing, other than a handful of i/o syscalls.
They're essentially two different technologies for two use cases. The OS threads are more robust and closer to the metal, but they are expensive to start up and switch between. However GT are small and cheap.
Another way to look at it is that there are only OS threads, and "virtual" or "green" threads are distinct concurrent tasks scheduled onto a pool of OS threads on the fly. The compiler inserts a bunch of book keeping to make scheduling those tasks easier. The only thing that makes them "thread like" is the API.
- zozbot234 4y agoSome operating systems implement standard OS threading API's on top of a pool of true "system threads". Notably, this even included some early Java implementations, before a 1-to-1 mapping between system and "user" threads became more popular for some reason.
- duped 4y agowhich makes a lot of sense once they have to map to logical cores