Posix執行緒程式設計指南(5)-Misc (轉)

worldblog發表於2007-08-16
Posix執行緒程式設計指南(5)-Misc (轉)[@more@]

Linux/thread/posix_thread/part5/author1">楊沙洲
2001 年 11 月

這是一個關於Posix執行緒的專欄。作者在闡明概念的基礎上,將向您詳細講述Posix執行緒庫API。本文是第五篇將向您講述pthread_self()、pthread_equal()和pthread_once()等雜項。

在Posix執行緒規範中還有幾個輔助函式難以歸類,暫且稱其為雜項函式,主要包括pthread_self()、pthread_equal()和pthread_once()三個,另外還有一個LinuxThreads非可移植性擴充套件函式pthread_kill_other_threads_np()。本文就介紹這幾個函式的定義和使用。


pthread_t pthread_self(void)

本函式返回本執行緒的識別符號。

在LinuxThreads中,每個執行緒都用一個pthread_descr結構來描述,其中包含了執行緒狀態、執行緒ID等所有需要的資料結構,此函式的實現就是線上程棧幀中找到本執行緒的pthread_descr結構,然後返回其中的p_tid項。

pthread_t型別在LinuxThreads中定義為無符號長整型。


int pthread_equal(pthread_t thread1, pthread_t thread2)

判斷兩個執行緒描述符是否指向同一執行緒。在LinuxThreads中,執行緒ID相同的執行緒必然是同一個執行緒,因此,這個函式的實現僅僅判斷thread1和thread2是否相等。

一次的操作
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))

本函式使用初值為PTHREAD_ONCE_INIT的once_control變數保證init_routine()函式在本程式執行序列中僅執行一次。

#include #include pthread_once_t once=PTHREAD_ONCE_INIT; void once_run(void) { printf("once_run in thread %d ",pthread_self()); } void * child1(void *arg) { int tid=pthread_self(); printf("thread %d enter ",tid); pthread_once(&once,once_run); printf("thread %d returns ",tid); } void * child2(void *arg) { int tid=pthread_self(); printf("thread %d enter ",tid); pthread_once(&once,once_run); printf("thread %d returns ",tid); } int main(void) { int tid1,tid2; printf("hello "); pthread_create(&tid1,NULL,child1,NULL); pthread_create(&tid2,NULL,child2,NULL); sleep(10); printf("main thread exit "); return 0; }



once_run()函式僅執行一次,且究竟在哪個執行緒中執行是不定的,儘管pthread_once(&once,once_run)出現在兩個執行緒中。

LinuxThreads使用互斥鎖和條件變數保證由pthread_once()指定的函式執行且僅執行一次,而once_control則表徵是否執行過。如果once_control的初值不是PTHREAD_ONCE_INIT(LinuxThreads定義為0),pthread_once()的行為就會不正常。在LinuxThreads中,實際"一次性函式"的執行狀態有三種:NEVER(0)、IN_PROGRESS(1)、DONE(2),如果once初值設為1,則由於所有pthread_once()都必須等待其中一個激發"已執行一次"訊號,因此所有pthread_once()都會陷入永久的等待中;如果設為2,則表示該函式已執行過一次,從而所有pthread_once()都會立即返回0。


void pthread_kill_other_threads_np(void)

這個函式是LinuxThreads針對本身無法實現的POSIX約定而做的擴充套件。POSIX要求當程式的某一個執行緒執行exec*在程式空間中載入另一個時,當前程式的所有執行緒都應終止。由於LinuxThreads的侷限性,該機制無法在exec中實現,因此要求執行緒執行exec前手工終止其他所有執行緒。pthread_kill_other_threads_np()的作用就是這個。

需要注意的是,pthread_kill_other_threads_np()並沒有透過pthread_cancel()來終止執行緒,而是直接向管理執行緒發"程式退出"訊號,使所有其他執行緒都結束執行,而不經過Cancel動作,當然也不會執行退出回撥函式。儘管LinuxThreads的實驗結果與文件說明相同,但程式碼實現中卻是用的__pthread_sig_cancel訊號來kill執行緒,應該效果與執行pthread_cancel()是一樣的,其中原因目前還不清楚。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-961040/,如需轉載,請註明出處,否則將追究法律責任。

相關文章