单核处理器上的单线程与多线程编程 [英] Single- vs. multi-threaded programming on a single core processor

查看:198
本文介绍了单核处理器上的单线程与多线程编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下编写在具有单个核的单个处理器上运行的多线程代码是否真的有任何优势吗?例如,一种处理文档页面以使页面与上述代码互斥的方法.

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.

请注意,我不是说应用程序"而是说代码段" -请看上面的示例.显然,拥有多线程应用程序会带来好处.

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.

推荐答案

仍然可以获得一些优势,但是它们有些特殊情况.

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.

如果您要处理多个潜在的阻塞资源(例如文件IO或GUI交互或其他),那么多线程至关重要.

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

这篇关于单核处理器上的单线程与多线程编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆