简体   繁体   English

"多个线程可以在多核处理器中并行运行(不是上下文切换)吗"

[英]Can multiple threads run in parallel (not context switching) in multi core processor

I have been reading that if there are say 2 threads and 2 cores , then each thread if allocated to different cores , they will be able to run concurrently or at the exact same time .我一直在阅读,如果有 2 个线程和 2 个内核,那么每个线程如果分配给不同的内核,它们将能够同时或同时运行。 Lets consider 2 threads T1 , T2 with run time of 10 sec each.让我们考虑 2 个线程 T1 、 T2 ,每个线程的运行时间为 10 秒。

Let's consider Single core first :<\/strong>让我们首先考虑单核:<\/strong>

If these 2 threads were to run in a single core, they would be running by context switching which will of course not be parallel execution but sequential, the thread scheduler will pick one and assign a slot to run.如果这两个线程要在单个内核中运行,它们将通过上下文切换运行,这当然不是并行执行而是顺序执行,线程调度程序将选择一个并分配一个插槽来运行。 So in single-core, it can't be possible that T1 is running at 10:00:00, and T2 is also running at 10:00:00 concurrently.所以在单核中,T1 不可能在 10:00:00 运行,而 T2 也同时在 10:00:00 运行。 So here run time of both threadsis 20sec所以这里两个线程的运行时间都是 20 秒

Now consider multi core:<\/strong>现在考虑多核:<\/strong>

Lets say T1 begins running on core 1 at 10:00:00 am Then is it possible that T2 also starts to run on core 2 at exactly 10:00:00 am ?假设 T1 在上午 10:00:00 开始在核心 1 上运行 那么 T2 是否也可能在上午 10:00:00 开始在核心 2 上运行?

If yes , this simply means that here the run time is halved - so total time taken to run both threads on multicore is 10 secs?如果是,这仅仅意味着这里的运行时间减半——所以在多核上运行两个线程的总时间是 10 秒? I highly doubt this but this is what I am reading , please clarify我非常怀疑这一点,但这是我正在阅读的内容,请澄清

"

Yes, you are right, multiple cores can run threads simultaneously ie parallel execution of multiple threads is possible if we have multiple cores.是的,您是对的,多个内核可以同时运行线程,即如果我们有多个内核,则可以并行执行多个线程。 So it may happen that in your case, T1 and T2 runs on the exact same time, depending on the scheduler.因此,在您的情况下,T1 和 T2 可能会在完全相同的时间运行,具体取决于调度程序。

In single core though, because it can only run single thread at a time, it has to stop processing the first thread to give chance to second thread, before giving chance to thread T2, it saves the state of T1 and switches over to T2 this in fact is Context switching.但是在单核中,因为一次只能运行一个线程,它必须停止处理第一个线程以给第二个线程机会,在给线程T2机会之前,它会保存T1的状态并切换到T2这个其实就是上下文切换。

You can check this by running a simple program of starting 2 or more threads and see if they prints the exact almost similar timestamp or not.您可以通过运行一个启动 2 个或更多线程的简单程序来检查这一点,看看它们是否打印出几乎完全相同的时间戳。

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM