How expensive is a context switch? Is it better to implement a manual task switch than to rely on OS

Posted by Vilx- on Stack Overflow See other posts from Stack Overflow or by Vilx-
Published on 2010-05-08T14:52:50Z Indexed on 2010/05/08 14:58 UTC
Read the original article Hit count: 210

The title says it all. Imagine I have two (three, four, whatever) tasks that have to run in parallel. Now, the easy way to do this would be to create separate threads and forget about it. But on a plain old single-core CPU that would mean a lot of context switching - and we all know that context switching is big, bad, slow, and generally simply Evil. It should be avoided, right?

On that note, if I'm writing the software from ground up anyway, I could go the extra mile and implement my own task-switching. Split each task in parts, save the state inbetween, and then switch among them within a single thread. Or, if I detect that there are multiple CPU cores, I could just give each task to a separate thread and all would be well.

The second solution does have the advantage of adapting to the number of available CPU cores, but will the manual task-switch really be faster than the one in the OS core? Especially if I'm trying to make the whole thing generic with a TaskManager and an ITask, etc?

© Stack Overflow or respective owner

Related posts about context-switch

Related posts about cost