并发和并行的区别

并发和并行的区别

并发(concurrent)与并行(parallel)是两个既相似而又不相同的概念。我们先来看一下英文的解释。

Concurrency is when two tasks can start, run, and complete in overlapping time periods. Parallelism is when tasks literally run at the same time, eg. on a multi-core processor.

Concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations.Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.

  • An application can be concurrent – but not parallel, which means that it processes more than one task at the same time, but no two tasks are executing at same time instant.
  • An application can be parallel – but not concurrent, which means that it processes multiple sub-tasks of a task in multi-core CPU at same time.
  • An application can be both parallel – and concurrent, which means that it processes multiple tasks concurrently in multi-core CPU at same time.
并发和并行的区别

并发是指多个事件在同一时间间隔发生,而并行是指多个事件在同一时刻发生。

  • 并发:在同一时刻只能有一条指令执行,但多个进程指令被快速的轮换执行,使得在宏观上具有多个进程同时执行的效果,但在微观上并不是同时执行的,只是把时间分成若干段,使多个进程快速交替的执行。
  • 并行:在同一时刻,有多条指令在多个处理器上同时执行。所以无论从微观还是从宏观来看,二者都是一起执行的。
并发和并行的区别
并发和并行的区别

若系统只有一个 CPU,则它不可能真正同时进行一个以上的线程,它只能把 CPU 运行时间划分成若干个时间段,再将时间段分配给各个线程执行,在一个时间段的线程代码运行时,其它线程处于挂起状态。这种方式称为并发。

当系统有一个以上 CPU,一个 CPU 执行一个线程的同时另一个 CPU 可以执行另一个线程,两个线程互不抢占 CPU 资源,可以同时进行,这种方式称为并行。

举例来说,假设有三个学生需要辅导作业,帮每个学生辅导完作业是一个任务。

  • 顺序执行:老师甲先帮学生A辅导,辅导完之后再取给B辅导,最后再去给C辅导。
  • 并发:老师甲先给学生A去讲思路,A听懂了自己书写过程,这期间甲老师去给B讲思路,讲完思路,B自己书写过程,这期间再去给C讲思路。这样老师就没有空着,一直在做事情。与顺序执行不同的是,顺序执行,老师讲完思路之后学生再写步骤,这期间老师是空闲的。
  • 并行:直接让三个老师甲、乙、丙,“同时”给三个学生辅导作业。
并发和并行的区别

你可能感兴趣的:(并发和并行的区别)