100次浏览 发布时间:2024-07-29 16:03:15
并发(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.
并发是指多个事件在同一时间间隔发生,而并行是指多个事件在同一时刻发生。
若系统只有一个 CPU,则它不可能真正同时进行一个以上的线程,它只能把 CPU 运行时间划分成若干个时间段,再将时间段分配给各个线程执行,在一个时间段的线程代码运行时,其它线程处于挂起状态。这种方式称为并发。
当系统有一个以上 CPU,一个 CPU 执行一个线程的同时另一个 CPU 可以执行另一个线程,两个线程互不抢占 CPU 资源,可以同时进行,这种方式称为并行。
举例来说,假设有三个学生需要辅导作业,帮每个学生辅导完作业是一个任务。