1. 程式人生 > >5-[多線程]-線程理論

5-[多線程]-線程理論

兩種 AC proc chang 線程 共享 裏的 進程的地址空間 AI

1、什麽是線程

在傳統操作系統中,每個進程有一個地址空間,而且默認就有一個控制線程
進程只是用來把資源集中到一起(進程只是一個資源單位,或者說資源集合)
線程才是cpu上的執行單位。

  技術分享圖片

技術分享圖片

多線程(即多個控制線程)的概念是,在一個進程中存在多個線程,多個線程共享該進程的地址空間, 

相當於一個車間內有多條流水線,都共用一個車間的資源。例如,北京地鐵與上海地鐵是不同的進程,

而北京地鐵裏的13號線是一個線程,北京地鐵所有的線路共享北京地鐵所有的資源,比如所有的乘客可以被所有線路拉。

2、多線程應用舉例

技術分享圖片

技術分享圖片

技術分享圖片

3、開啟進程的兩種方式:threading模塊

  • multiprocess模塊的完全模仿了threading模塊的接口,二者在使用層面,有很大的相似性,因而不再詳細介紹

技術分享圖片技術分享圖片

技術分享圖片技術分享圖片

技術分享圖片

4、線程與進程的區別

  1. Threads share the address space of the process that created it; processes have their own address space.
  2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  4. New threads are easily created; new processes require duplication of the parent process.
  5. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
  6. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

技術分享圖片

5

5-[多線程]-線程理論