并发 线程交替执行_并发和并行的区别

9912e6073447482e8508e0d734820793

并发(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.
d8f8c5d92f8fdef6eac49bbe0542f851.png

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

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

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

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

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

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

扩展阅读:

并发编程的应用和方法介绍

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值