一、什么是線程?
- 線程是一種執(zhí)行流,也是一種任務(wù)流,因此線程也具有5個(gè)狀態(tài),可參與時(shí)間片輪轉(zhuǎn);
- 線程必須依附于進(jìn)程而存在;
- 進(jìn)程即OS分配資源的基本單位,也是執(zhí)行單位,
線程僅是一個(gè)執(zhí)行單位,OS只給它運(yùn)行必要的資源(棧); - 每個(gè)線程都有一個(gè)id,但這個(gè)id只是保證在同一個(gè)進(jìn)程里不一樣。
二、線程相關(guān)函數(shù)
創(chuàng)建線程
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr, //線程屬性
void *(*start_routine)(void*), //線程入口函數(shù)
void *arg);
等待線程結(jié)束
int pthread_join(pthread_t thread, void **retval);
- 等待指定線程退出;
- 對(duì)已退出的線程做善后;
- 獲取已退出的線程的返回值:成功為0,失敗非0。
創(chuàng)建分離的線程
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;
}
//不要調(diào)用join
線程的退出
void pthread_exit(void *retval); //退出
線程的取消
pthread_cancel:其作用是給指定的線程發(fā)送取消請(qǐng)求,但它只是發(fā)出請(qǐng)求,線程是否取消則不在其考慮范圍之內(nèi)。
三、關(guān)于資源沖突
資源沖突的前提
- 多任務(wù)并行執(zhí)行;
- 存在共享資源;
- 同時(shí)操作共享資源。
這種同時(shí)使用共享資源導(dǎo)致的問(wèn)題,專業(yè)上被稱為競(jìng)態(tài)問(wèn)題。
如何避免競(jìng)態(tài)
設(shè)法不要讓多任務(wù)同時(shí)使用該共享資源。
解決競(jìng)態(tài)問(wèn)題的手段被稱為同步機(jī)制。
典型的競(jìng)態(tài)問(wèn)題
-
同步問(wèn)題
解決辦法:
定義一個(gè)信號(hào)量類型的變量;
初始化該變量;
......
信號(hào)量P操作;
...... //臨界區(qū)(需要使用共享資源的一段代碼)
信號(hào)量V操作;
......
-
互斥問(wèn)題
解決辦法:
定義一個(gè)信號(hào)量類型的變量;
初始化該變量(信號(hào)量的計(jì)數(shù)牌初始值為0);
A任務(wù)代碼;
......
...... //臨界區(qū)(需要使用共享資源的一段代碼)
信號(hào)量V操作;
......
B任務(wù)代碼;
......
信號(hào)量P操作;
...... //臨界區(qū)(需要使用共享資源的一段代碼)
四、系統(tǒng)為線程提供的同步機(jī)制
線程信號(hào)量
- 頭文件: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);
線程讀寫(xiě)鎖
- 頭文件: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);
- 阻塞寫(xiě)鎖P操作:int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock,NULL);
- 非阻塞讀鎖P操作:int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock,NULL);
- 非阻塞寫(xiě)鎖P操作:int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock,NULL);
- V操作:int pthread_rwlock_unlock(pthread_rwlock_t *rwlock,NULL);