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

后端 未结 3 1429
野的像风
野的像风 2021-02-01 07:54

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 pr

3条回答
  •  余生分开走
    2021-02-01 08:19

    On a single core processor, an application that uses asynchronous (non-blocking) I/O will be slightly more efficient than one that uses multiple blocking threads, because it avoids the overhead of context switching between threads.

    Also, asynchronous I/O scales better than blocking I/O in threads because the overhead per extra I/O operation is minimal compared to the overhead of creating a new thread.

    Having said that, you shouldn't generally use single-threaded asynchronous I/O in new applications because almost all new processors are multicore. Instead you should still use asynchronous I/O, but split the work amongst a set of worker threads using something like a thread pool. Your system documentation will tell you the ideal number of worker threads; usually it is equal to the number of processing cores available.

    Edit: On the Windows platform at least, the async/await pattern in .NET is the modern way to perform asynchronous I/O. It makes this pattern as trivially easy to write as the old blocking I/O pattern. There is almost no excuse for writing blocking I/O now.

提交回复
热议问题