併發和並行的區別

中央處理器 算法集市 2019-06-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.

  • 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講思路。這樣老師就沒有空著,一直在做事情。與順序執行不同的是,順序執行,老師講完思路之後學生再寫步驟,這期間老師是空閒的。
  • 並行:直接讓三個老師甲、乙、丙,“同時”給三個學生輔導作業。
併發和並行的區別

擴展閱讀:

併發編程的應用和方法介紹

相關推薦

推薦中...