《unix高階環境程式設計》執行緒控制 同步屬性

2021-06-27 06:04:56 字數 2894 閱讀 8608

互斥量屬性可以用 pthread_mutexattr_t 資料結構來進行操作,屬性的初始化操作如下:

[cpp]view plain

copy

/* 同步屬性 */

/* 互斥量屬性 */

/** 函式功能:初始化互斥量屬性;

* 返回值:若成功則返回0,否則返回錯誤編碼;

* 函式原型:

*/#include 

intpthread_mutexattr_init(pthread_mutexattr_t *attr);  

intpthread_mutexattr_destroy(pthread_mutexattr_t *attr);  

/** 說明:

* pthread_mutexattr_init函式用預設的互斥量屬性初始化pthread_mutexattr_t結構;

* 兩個屬性是程序共享屬性和型別屬性;

*//*

* 函式功能:獲取或修改程序共享屬性;

* 返回值:若成功則返回0,否則返回錯誤編碼;

* 函式原型:

*/#include 

intpthread_mutexattr_getpshared(

const

pthread_mutexattr_t *attr, 

int*pshared);

//獲取互斥量的程序共享屬性

intpthread_mutexattr_setpshared(pthread_mutexattr_t *attr, 

intpshared);

//設定互斥量的程序共享屬性

/** 說明:

* 程序共享互斥量屬性設定為pthread_process_private時,允許pthread執行緒庫提供更加有效的互斥量實現,這在多執行緒應用程式中是預設的;

* 在多個程序共享多個互斥量的情況下,pthread執行緒庫可以限制開銷較大的互斥量實現;

*//*

* 函式功能:獲取或修改型別屬性;

* 返回值:若成功則返回0,否則返回錯誤編碼;

* 函式原型:

*/int

pthread_mutexattr_gettype(

const

pthread_mutexattr_t *attr, 

int*type);

//獲取互斥量的型別屬性

intpthread_mutexattr_settype(pthread_mutexattr_t *attr, 

inttype);

//修改互斥量的型別屬性

互斥量型別的控制如下所示:

[cpp]view plain

copy

互斥量型別   沒有解鎖時再次加鎖   不占用時解鎖  已解鎖時再次解鎖  

pthread_mutex_normal     死鎖 未定義 未定義  

pthread_mutex_errorcheck     返回錯誤   返回錯誤    返回錯誤  

pthread_mutex_recursive  允許 返回錯誤    返回錯誤  

pthread_mutex_default    未定義    未定義 未定義  

讀寫鎖屬性只有程序共享屬性,其屬性操作如下:

[cpp]view plain

copy

/* 讀寫鎖屬性 */

/** 函式功能:初始化讀寫鎖屬性;

* 返回值:若成功則返回0,否則返回錯誤編碼;

* 函式原型:

*/#include 

intpthread_rwlockattr_init(pthread_rwlockattr_t *attr);  

intpthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);  

/** 說明:

* 讀寫鎖的唯一屬性就是程序共享,該屬性與互斥量的程序共享相同;

*//*

* 函式功能:獲取或修改讀寫鎖的程序共享屬性;

* 返回值:若成功則返回0,否則返貨錯誤編碼;

* 函式原型:

*/int

pthread_rwlock_getpshared(

const

pthread_rwlockattr_t *attr, 

int*pshared);  

intpthread_rwlock_setpshared(pthread_rwlockattr_t *attr, 

intpshared);  

條件變數也只有程序共享屬性,其操作如下:

[cpp]view plain

copy

/* 條件變數屬性 */

/** 函式功能:初始化條件變數屬性;

* 返回值:若成功則返回0,否則返回錯誤編碼;

* 函式原型:

*/#include 

intpthread_condattr_init(pthread_condattr_t *attr);  

intpthread_condattr_destroy(pthread_condattr_t *attr);  

/** 函式功能:獲取或修改程序共享屬性;

* 返回值:若成功則返回0,否則返回錯誤編碼;

* 函式原型:

*/#include 

intpthread_condattr_getpshared(

const

pthread_condattr_t *attr, 

int*pshared);  

intpthread_condattr_setpshared(pthread_condattr_t *attr, 

intpshared);  

UNIX高階程式設計 執行緒控制

第12章執行緒控制 12.1 執行緒的四大屬性 pthread attr t int pthread attr init pthread attr t attr 初始化執行緒屬性 int pthread attr destroy pthread attr t attr 釋放執行緒屬性 如果不關心執行...

Unix環境高階程式設計 程序控制 二

一 函式wait 和waitpid 今天我們繼續通過昨天那個死爹死兒子的故事來講 便於記憶 現在看看 wait 和waitpid 函式。include pid t wait int statloc pid t waitpid pid t pid int statloc int options 若成功...

Unix環境高階程式設計 程序控制(1)

使用者id和組id 在設計應用時,總是試圖使用最小特權 least privilege 模型,依據此模型,程式應當只具有為完成給定任務所需的最小許可權,可用setuid函式設定實際使用者id和有效使用者id。用setgid函式設定實際組id和有效組id。下表總結了更改3個使用者id的不同方法 直譯器...