# Threads ###### tags: `OS Note Pro` [TOC] ## Threads Introduction 簡單來說thread就是簡化版的process,是系統真正處理的最小單位。因此一般來說,process可以視為single-thread (maybe)。但process是比較heavy的。 <font color="red">Why we need thread?</font> Threads 能夠共享process的資訊,如:Gloable variable、Dynamic memory space等,並且實行平行處理,同時執行多個threads,這是單一個process無法辦到的,而且process之間的溝通會更花時間。 <font color="blue">Feature:</font> 然而,每一thread都有各自獨立的運算單元(空間?),如register、stack(local variable)等(program counter、thread id)。這是達到獨立運算的關鍵。而同一個process的thread共享了code section、memory(data) section以及OS resource。 <font color="green">Example:</font> 1. 網頁瀏覽器: 一個網頁除了要同時顯示內容之外,還要一方面能夠接收來自網路的資料,這就需要threads。 2. Web server: Server需要一邊處理使用者的request還要,再線等待用戶端,假如只有一個process效率會非常差。 :::spoiler 名詞補充: address space An address space defines a range of discrete addresses, each of which may correspond to a network host, peripheral device, disk sector, a memory cell or other logical or physical entity. ::: :::success Benefit of multithread: 1. Responsive : 能夠一方面回應使用者,一方面執行運算 2. Resource sharing : 能共享OS resource 3. Utilization of mulitprocesser architcher : 在multiprocesser達到平行化處理 4. Economy : Create、memory management都比較快(比process) ::: :::warning Multithreading 的挑戰 1. Dividing activity 2. Balance 3. Data split 4. Data dependent : synchronization ::: ## User Thread & Kernel Thread 一般的programer只需要使用Thread library就可以產生user level的threads,但要讓硬體實際執行,需要經過許多layer,包括作業系統甚至到CPU core內部都有scheduler來處理。而kernel thread就是作業系統核心用來接應user thread。 <font color="blue">Faster <-> Slower</font> **User Thread**: 因為只要透過Thread library就可以產生,所以執行速度和管理速度快 於kernel thread。 **Kernel Thread**: 因為是在系統內部處理,且須考量到security等因素,所以產生kernel thread是比user thread慢的。但相對於user thread,只要有一個thread block 仍然可以靠scheduler來讓其他的 kernel 來處理。 <font color="blue">Three type Bind:</font> 1. **One to one**: 目前最常見的方法,能夠達到較好的同步處理,但缺點是user thread會受限於kernel thread的數量,而且kernel thread是相對不好產生且產生較慢的。 2. **Many to one**: 好處是user thread好產生,整體速度快,但一旦有其中一個thread卡住了(執行了I/O或sleep等等),那其他的thread就必須等。 3. **Many to many**: 較為複雜,雖然能解決many2one的缺點,但系統必須要執行更複雜的運算來分配誰對誰,以整體來說並不一定比one2one快。 ## Pthread 普遍來說Process與Process之間的溝通是透過shared memory。 <font color="red">Difficulty:</font> 1. Synchronize 2. Dead lock 3. cache coherence 對於不一樣的hardware會有不一樣版本的thread,而為了增將相容性,所以就有了unix-like的interface for Pthread。 **POSIX(Portable Operating system interface)** **Pthread**就是implement of POISX stantard (可以看成library) :::success Pthread是可以執行在user-level的。 :::