搜尋此網誌

網頁

2010年3月24日 星期三

Semaphone 觀念 & Pthread Programing

1.

if(semaphone){

critical section (放置需保護的資料)

}

2. thread可分為user thread(POSIX thread) 與 kernel thread兩種

3. 寫multi thread 的程式時,編譯記得加上 -lpthread

4. pthread_create(thread_id, thread_attr, thread_func, thread_argu) 其中:
thread_argu為傳遞給thread func 的參數
thread_id 為指向thread_id的指標
thread_func 為指向therad function 的指標 資料型別為 (void *)
thread_attr 指向thread attribute 的指標 NULL 則表示create出來的thread為joinable Thread

5. join Thread 機制可以確保thread 執行的工作要先完成,後續的process/thread才會往下執行。

6. join_thread2.c 編譯執行後會出現 segmentation fault !

7. join_thread3.c 中示範如何讓process與thread依照期望的順序執行完成,在thread中亦可妥善利用pthread_join() 做等待(特定thread工作結束)。

8. Pthread programing 練習: https://computing.llnl.gov/tutorials/pthreads/

9. GNI/Linux 實做的semaphones可以分為 :
thread semaphones
process semaphones

10. Semaphores 使用方式:

Semaphones S ; // 初始化變數S, 一般設定為'1'

P(S); //wait operation
EnterCriticalSection();
V(S); // post operation

11. Race Condition 發生在以下2種情況下
(1) 多個process同時concurrent執行且共用相同資源(EX:同一個結構變數)

(2) 在多工與分時系統下會產生,因程式碼執行順序而出現的競賽問題

12. (猜測)semaphones 可以分為:

kernel semaphones : 呼叫 sem_init()初始化
down_interruptable();

{
critical section
}

up();

user semaphones: 呼叫sema_init()初始化
sem_wait();
{
critical section
}
sem_post();

13. 不能在critical section 中直接呼叫 sleep(造成deadlock) , 試著思考為什麼? 因為Atomic特性,不能有停頓出現在critical section。

14. 利用程式碼特性善用區域變數,最後處理完的結果用semaphore保護起來放到,減少semaphore的使用次數

15. 思考 先 open() 再 fork() 跟先fork() 再 open() 的差別在哪? 先open 再 fork的話,parent 與 child process 會共用同一個struct file 的資源。

16. 實做sleep_on 的簡單步驟:

(1) init_waitqueue_entry()
(2) add_waitqueue
(3) current->state = TASK_INTERRUPTIBLE
(4) schedule() // 在critical section外呼叫

17. taskqueue 用於對function進行排程時使用,為進化版的kernel timer,linux kernel 2.6 進化為workqueue,具體做法: queue_task(&cdata->cdata_tq,&tq_timer)。

18. kernel thread 也可以被排程(需特別將kernel thread丟到queue中),形成具有time slice 的kernel space function

19. 在critical section 中,還是可以接收硬體的中斷(猜測),而sleep則不允許!

20. mutex,semapores , spin-lock的差別在哪? spin-lock為driver另一組semaphone函數(busy loop/waiting) ,用於中斷模式下使用, semaphores則是先讓user space process 去 sleep。

21. down, up 函數是使用wait queue做等待(用於等待時間長) <-> spin-lock 用 busy loop方式做等待(用於等待時間短)

22. 單處理器不會出現P進入critical section 而 Q在外面等待的情況,SMP則會出現!所以在單處器使用semaphores / spin-lock 比較沒有意義,但建議還是加上去。

23. linux 2.4 kernel 中有變化型的spin-lock可以在critical section 下關閉外部中斷。

24. hold semaphores

25. 留意 linux 2.4 kernel底下的driver , 其 spin-lock的實作是空的。

26. spin-lock在多處理器才有意義, 2.4 kernel不支援ARM的多核心處理器(猜測)。

27. 在單處理器的架構之下,並不會P停下來後Q並不會在semaphores外面等待,而是否會有同步問題則需看實做的架構而定(基本上還是會出現同步問題)。

28. semaphores 系列函數: down , up

spin-lock系列函數: spin_lock , spin_unlock

沒有留言:

張貼留言