Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single- vs. multi-threaded programming on a single core processor

Can someone please explain if there's really any advantage to writing a multi-threaded piece of code that runs on a single processor with a single core? E.g., a method that processes document pages such that the pages are mutually exclusive w/r/t the aforementioned piece of code.

At first glance, it doesn't seem like there'd be an advantage because true multi-threading is not possible. I.e., the OS would have to context switch the threads anyway. I'm wondering if just coding something in a single-threaded manner could actually be more efficient.

Clearly, there are plenty of cases where writing multi-threaded code makes sense, but again, my question gets to whether there's really an advantage of doing so when the application is running on a single-core processor.

EDIT: note, that I did not say "application" but rather "piece of code" - look at my example above. Clearly there are benefits to having a multi-threaded application.

like image 493
icfantv Avatar asked Dec 09 '13 17:12

icfantv


2 Answers

There are still advantages to be gained, but they're a bit situational.

  • In many cases, giving the thing multiple threads will allow it to claim more system resources from other processes. This is finicky to balance, and each thread you introduce adds a bit of overhead, but it can be a reason.

  • If you are dealing with multiple potentially blocking resources - like file IO or GUI interaction or whatnot, then multithreading can be vital.

like image 194
Ben Barden Avatar answered Oct 07 '22 18:10

Ben Barden


Yes, multi-threading is useful in a single core. If one thread in an application gets blocked waiting for something (say data from the network card or waiting for the disk to write data), the CPU can switch to another thread to keep working.

BeOS was written with pervasive multithreading in mind, even in a time of single core processors. The result was a very responsive OS, though a rather difficult OS to program for.

like image 11
BergQuester Avatar answered Oct 07 '22 18:10

BergQuester