Threads the smallest sequence of programmed instructions that can be managed independently Process & Thread 一個Process可以有多個Thread 同一個Process內的Thread使用相同的Memory Space, 但這些Thread各自擁有其Stack。 作業系統會根據Thread的優先權以及已經用掉的CPU時間, 在不同的Thread作切換,以讓各個Thread都有機會執行。 User Thread v.s Kernel Thread kernel thread的功用 1. 處理只能在kernel space做的事情 -- device driver 2. 處理只能在kernel space做的事情,協助user program -- system call 3. daemon的使用, 因為kernel thread的context switch相對於user process來說是比較便宜的, 所以對需要固定時間就執行一次的daemon來說,以kernel thread的形式來呈現是最好的。 Kernel threads are used to: 1.Provide privileged(特權) services to applications (such as syscall). 2.Keep track of what all is running on the system. Many(usr)-to-One(kernel) If your applications make a heavy use of system calls, the more user threads per kernel thread, the slower your applications will run, because the kernel thread will become a bottleneck(瓶頸), since all system calls will pass through it. One-to-Many If you're programs rarely use system calls (or other kernel services), you can assign a large number of user threads to a kernel thread without much performance penalty(沒有太大的性能損失). Trade-off 可以增加kernel thread的數量, 使個別的usr thread對syscall的響應更快速 但會增加系統的負擔,所以需要取平衡 創建user process的方法是有三個API: fork, vfork, clone 創建user thread的方法主要是使用thread library: pthread_create 創建kernel thread的方法有兩種API: kernel_thread, kthread_create kernel_thread v.s. kthread_create kernel_thread創建kernel thread, 但是在執行函數里面必須用daemonize釋放資源並掛到init下, 還需要用completion等待這一過程的完成。 kthread_create是比較正牌的創建函數, 這個不必要調用daemonize, 用這個創建的kernel thread都掛在了kthread線程下。 P.S. Daemon 是一個常駐記憶體的背景行程,通常負責系統中的某個服務。 1.stand alone: 常駐記憶體且持續佔用系統資源,快速反應 (httpd (WWW)、iptables (firewall)、smbd (SAMBA)、named (DNS)) 2.super daemon: 總管許多服務的程式。 當有要求送來時根據要求封包的內容 (IP 與 port) 將此要求轉送給實際負責的服務程式來處理(平常處於sleep狀態) 不占資源但是反應慢 Context Switch(Multi-Processing的實踐) CPU一瞬間只能處理一筆資料執行一個程式 一個工作須要成千上萬次的執行, 所以也不至於每執行一個指另就換下一個工作 因為資料通常放在記憶體或暫存器 (Register, 就當作較快的記憶體) CPU 能夠執行的記憶體才能執行, 這資料叫做 Context (文本) 因為Context放不下,所以通常會放在硬碟,將資料移入的動作就叫Context Switch
參考資料
http://gic4107.blogspot.tw/2013/08/user-process-user-thread-kernel-thread.html
http://stackoverflow.com/questions/1178785/relationship-between-a-kernel-and-a-user-thread
http://eeepage.info/daemon-what/
http://gene.speaking.tw/2011/03/context-switch.html
Advertisements