Linux併發 筆記

2021-09-24 14:58:18 字數 1937 閱讀 9974

執行緒不像程序那樣,不是按照嚴格的父子層次來組織的。和乙個程序相關的執行緒組成乙個對等執行緒池(a pool of peers)。對等(執行緒)池概念的主要影響是,乙個執行緒可以殺死它的任何對等執行緒,或者等待它的任意對等執行緒終止;進一步來說,每個對等執行緒都能讀寫相同的共享資料。

/* man pthread_attr_init */

typedef struct

pthread_attr_t;

執行緒的繫結,牽涉到另外乙個概念:輕程序(lwp:light weight process)。輕程序可以理解為核心執行緒,它位於使用者層和系統層之間。系統對執行緒資源的分配、對執行緒的控制是通過輕程序來實現的,乙個輕程序可以控制乙個或多個執行緒。預設狀況下,啟動多少輕程序、哪些輕程序來控制哪些執行緒是由系統來控制的,這種狀況即稱為非繫結的。繫結狀況下,即某個執行緒固定的"綁"在乙個輕程序之上。被繫結的執行緒具有較高的響應速度,這是因為cpu時間片的排程是面向輕程序的,繫結的執行緒可以保證在需要的時候它總有乙個輕程序可用。通過設定被繫結的輕程序的優先順序和排程級可以使得繫結的執行緒滿足諸如實時反應之類的要求。

設定執行緒繫結狀態的函式為pthread_attr_setscope,它有兩個引數,第乙個是指向屬性結構的指標,第二個是繫結型別,它有兩個取值:pthread_scope_system(繫結的)和pthread_scope_process(非繫結的)。

pthread_attr_setscope(&attr, pthread_scope_system);
可結合的執行緒能夠被其他執行緒收回其資源和殺死;在被其他執行緒**之前,它的儲存器資源(如棧)是不釋放的

分離的執行緒是不能被其他執行緒**或殺死的,它的儲存器資源在它終止時由系統自動釋放。

pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)

pthread_create_detached(分離執行緒)和 pthread _create_joinable(非分離執行緒)

注意:如果設定乙個執行緒為分離執行緒,而這個執行緒執行又非常快,它很可能在pthread_create函式返回之前就終止了,它終止以後就可能將執行緒號和系統資源移交給其他的執行緒使用,這樣呼叫pthread_create的執行緒就得到了錯誤的執行緒號。採取一定的同步措施,最簡單的方法之一是可以在被建立的執行緒裡呼叫pthread_cond_timewait函式,讓這個執行緒等待一會兒,留出足夠的時間讓函式pthread_create返回。

程序內的所有執行緒共享程序的資料空間,因此全域性變數為所有執行緒所共有。

可以建立執行緒私有資料(thread-specific date)tsd,**程內部,私有資料可以被各個函式訪問,但對其他執行緒是遮蔽的。

為每個執行緒資料建立乙個鍵,它和這個鍵相關聯,在各個執行緒裡,都使用這個鍵來指代執行緒資料,但在不同的執行緒裡,這個鍵代表的資料是不同的,在同乙個執行緒裡,它代表同樣的資料內容。

建立私有資料的函式有4個:pthread_key_create(建立), pthread_setspecific(設定), pthread_getspecific(獲取), pthread_key_delete(刪除)。

#include int pthread_key_creadte(pthread_key_t *key,void (*destr_fuction) (void *));

int pthread_setspecific(pthread_key_t key,const void * pointer));

void * pthread_getspecific(pthread_key_t key);

int pthread_key_delete(ptherad_key_t key);

linux開發筆記

source etc profile12 3456 78910 1112 1314 1516 1718 19 desktop entry encoding utf 8 name eclipse comment eclipse ide exec home amarsoft software eclip...

多執行緒高併發筆記二

併發主要有三塊知識點 synchronized 同步容器 threadpool,executor lock reentrantlock lock lock new reentrantlock 公平鎖 lock lock new reentrantlock true void m1 boolean f...

Linux驅動開發筆記(二)

linux驅動開發的基本框架 define led major 200 define led name led static int led open struct inode inode,struct file filp static int led release struct inode in...