3 ms·
Operating system threads have two big disadvantages. You also design the code differently, since one schedule is cooperative and the other is preemptive. First
by jandrewrogers 10y ago
Operating system threads have two big disadvantages. You also design the code differently, since one schedule is cooperative and the other is preemptive.
First, OS context switching is much more expensive in terms of overhead compared to lightweight contexts like fibers. A highly optimized user-controlled context-switching scheme can be barely more expensive than a function call. Context switching OS threads, even when highly optimized, is much more expensive than you might assume, microseconds compared to a few dozen clock cycles, which adds up if you need to switch contexts frequently. In many software systems, the computational cost of the OS context switch can be higher than the computational cost of the real work done during that time slice (i.e. >50% CPU overhead due to context switching) and you end up doing a lot of optimization work trying to avoid this situation, often by implementing something that looks suspiciously like user-space coroutines.
Second, and I would argue more importantly, the operating system provided thread schedule, through no fault of its own, is often pretty terrible for concurrent/distributed/parallel systems. The operating system simply lacks the runtime context to optimally determine (1) when to switch contexts and (2) the right thread to switch to. In practice, this leads to a lot more context switching, and wasteful context switching, with its high overhead than would ever occur if you designed your own schedule. The impact is not small at all, a poor schedule can seriously damage CPU cache locality.