一、什么是線程?
- 線程是一種執行流,也是一種任務流,因此線程也具有5個狀態,可參與時間片輪轉;
- 線程必須依附于進程而存在;
- 進程即OS分配資源的基本單位,也是執行單位,
線程僅是一個執行單位,OS只給它運行必要的資源(棧); - 每個線程都有一個id,但這個id只是保證在同一個進程里不一樣。
二、線程相關函數
創建線程
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr, //線程屬性
void *(*start_routine)(void*), //線程入口函數
void *arg);
等待線程結束
int pthread_join(pthread_t thread, void **retval);
- 等待指定線程退出;
- 對已退出的線程做善后;
- 獲取已退出的線程的返回值:成功為0,失敗非0。
創建分離的線程
pthread_t tid;
int ret = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); //detached
ret = pthread_create(&tid,&attr,StartThread,NULL);
if(ret != 0)
{
printf("pthread_create failed\n");
pthread_attr_destroy(&attr);
return 1;
}
//不要調用join
線程的退出
void pthread_exit(void *retval); //退出
線程的取消
pthread_cancel:其作用是給指定的線程發送取消請求,但它只是發出請求,線程是否取消則不在其考慮范圍之內。
三、關于資源沖突
資源沖突的前提
- 多任務并行執行;
- 存在共享資源;
- 同時操作共享資源。
這種同時使用共享資源導致的問題,專業上被稱為競態問題。
如何避免競態
設法不要讓多任務同時使用該共享資源。
解決競態問題的手段被稱為同步機制。
典型的競態問題
-
同步問題
解決辦法:
定義一個信號量類型的變量;
初始化該變量;
......
信號量P操作;
...... //臨界區(需要使用共享資源的一段代碼)
信號量V操作;
......
-
互斥問題
解決辦法:
定義一個信號量類型的變量;
初始化該變量(信號量的計數牌初始值為0);
A任務代碼;
......
...... //臨界區(需要使用共享資源的一段代碼)
信號量V操作;
......
B任務代碼;
......
信號量P操作;
...... //臨界區(需要使用共享資源的一段代碼)
四、系統為線程提供的同步機制
線程信號量
- 頭文件:smaphore.h
- 類型:sem_t
- 初始化:int sem_init(sem_t *sem, int pshared, unsigned int value);
- 清理:int sem_destory(sem_t *sem);
- P操作:int sem_wait(sem_t *sem);
- V操作:int sem_post(sem_t *sem);
線程互斥量
- 頭文件:pthread.h
- 類型:pthread_mutex_t
- 初始化:int pthread_mutex_init(pthread_mutex_t *mutex,NULL);
- 清理:int pthread_mutex_destory(pthread_mutex_t *mutex,NULL);
- 阻塞P操作:int pthread_mutex_lock(pthread_mutex_t *mutex,NULL);
- 非阻塞P操作:int pthread_mutex_trylock(pthread_mutex_t *mutex,NULL);
- V操作:int pthread_mutex_unlock(pthread_mutex_t *mutex,NULL);
線程讀寫鎖
- 頭文件:pthread.h
- 類型:pthread_rwlock_t
- 初始化:int pthread_rwlock_init(pthread_rwlock_t *rwlock,NULL);
- 清理:int pthread_rwlock_destory(pthread_rwlock_t *rwlock,NULL);
- 阻塞讀鎖P操作:int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock,NULL);
- 阻塞寫鎖P操作:int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock,NULL);
- 非阻塞讀鎖P操作:int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock,NULL);
- 非阻塞寫鎖P操作:int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock,NULL);
- V操作:int pthread_rwlock_unlock(pthread_rwlock_t *rwlock,NULL);