linux第12天 執行緒

2022-04-29 10:30:10 字數 1072 閱讀 3283

今天主要學習了共享記憶體,訊號量的封裝,還有執行緒.

posix執行緒庫

與執行緒有關的函式構成了乙個完整的系列,絕大多數函式的名字都是以「pthread_」打頭的

要使用這些函式庫,要通過引入頭文

鏈結這些執行緒函式庫時要使用編譯器命令的「-lpthread」選項

pthread_create函式

功能:建立乙個新的執行緒,在主線程裡呼叫

原型int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);

引數thread:返回執行緒id

attr:設定執行緒的屬性,attr為null表示使用預設屬性

start_routine:是個函式位址,執行緒啟動後要執行的函式

arg:傳給執行緒啟動函式的引數

返回值:成功返回0;失敗返回錯誤碼,而不是設定全域性變數errno

pthread_join函式

功能:等待執行緒結束,在主線程裡呼叫

原型int pthread_join(pthread_t thread, void **value_ptr);

引數thread:執行緒id

value_ptr:它指向乙個指標,後者指向執行緒的返回值

void *p = null;

pthread_join(tid, &p);這樣呼叫

返回值:成功返回0;失敗返回錯誤碼

pthread_cancel函式

功能:取消乙個執行中的執行緒

原型int pthread_cancel(pthread_t thread);

引數thread:執行緒id

返回值:成功返回0;失敗返回錯誤碼

posix互斥鎖api

建立乙個鎖

pthread_mutex_t mutex = pthread_mutex_initializer;

pthread_mutex_init(&mutex );

臨界區,同時只有乙個執行緒能在裡面執行

pthread_mutex_unlock(&mutex);

第22天 執行緒的建立(有栗子)

執行緒的建立主要有兩種方法,第一種是繼承thread類,第二種是實現runnable介面。下面就以兩個栗子來引入這兩種建立執行緒的方法。1.繼承thread類 public class mythread extends thread public void run 重寫run 方法 在本慄中,如果不...

千鋒學習的第27天 執行緒

千鋒馬海超 千鋒學習的第27天 一 乙個單cpu的機器,如何同時執行多個執行緒?請簡述其原理 多執行緒等待os時間片,巨集觀並行,實際序列實現。二 執行緒的建立 有以下 public class example implements ruunable public static void main ...

黑馬程式設計師 第26天 執行緒2

asp.net unity開發 net培訓 期待與您交流!原來執行緒都有自己預設的名稱,thread 編號,該編號從0開始 static thread currentthread 獲取當前執行緒物件 getname 獲取執行緒名稱 設定執行緒名稱 setname或者建構函式 建立執行緒的第二種方式 ...