11.1 引言
11.2 線程概念
11.3 線程標識
- 使用函數來比較兩個線程ID;Linux 2.4.22使用無符號長整型標識pthread_t數據類型;Solaris 9用pthread_t數據類型表示爲無符號數。FreeBSD 5.2.1和MAC OS X 10.3用一個指向pthread_t結構的指針表示pthread_t數據類型;
#include<pthread.h> int pthread_equal(pthread_t td1, pthread_t td2); //返回值:若相等則返回非0值,否則返回0
- 線程獲取自己的線程ID;
#include<pthread.h> pthread_t pthread_self(void); // 返回值:調用線程的線程ID
11.4 線程創建
- 新增的線程調用創建函數;
#include<pthread.h> int pthread_create(pthread_t *tid, pthread_attr_t *attr, void *(*start_rtn)(void *), void *arg); // 返回值:若成功返回0,否則返回錯誤編號
11.5 線程終止
- 單個線程可以通過三種方式退出,在不終止整個進程的情況下停止它的控制流;
- 線程只是從啓動例程中返回,返回值是線程的退出碼;
- 線程可以被同一個進程的其他線程取消,調用取消方法;
- 線程本身調用退出方法;其中pthread_join可以訪問前面退出時的指針。
#include<pthread.h> void pthread_exit(void *rval_ptr); int pthread_join(pthread_t tid, void **rval_ptr); // 若成功返回0,否則返回錯誤碼 int pthread_cancel(pthread_t tid); // 若成功返回0,否則返回錯誤碼
- 線程退出時調用清理函數;當線程執行以下操作時執行清理函數,調用順序與註冊順序相反。
- 調用pthread_exit()時;
- 響應取消請求時;
- 以非0參數調用pthread_clean_up()方法時;
#include <pthread.h> void pthread_cleanup_push( void(*rtn)(void *), void *arg); void pthread_cleanup_pop(int execute);
11.6線程同步
- 互斥量
#include<pthread.h> int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr); int pthread_mutex_destroy(pthread_mutex_t *mutex); // 成功返回0, 否則返回錯誤碼 int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); //成功返回0,否則返回錯誤碼
- 避免死鎖
- 讀寫鎖
#include<pthread.h> int pthread_rwlock_init(pthread_rwlock_t *rwlock, pthread_rwlockattr_t *attr); int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); // 成功返回0,否則返回錯誤碼 int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); // 成功返回0,否則返回錯誤碼 int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
- 條件變量
#include<pthread.h> int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *attr); int pthread_cond_destroy(pthread_cond_t *cond); // 成功返回0,否則返回錯誤碼 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *timeout); // 成功返回0,否則返回錯誤碼 int pthread_cond_signal(pthread_cond_t *cond); int pthread_cond_broadcast(pthread_cond_t *cond); // 成功返回0,否則返回錯誤碼