Linux 執行緒相關函式
- 1、pthread_create 函式
- 2、pthread_join 函式
- 3、互斥鎖 pthread_mutex_t 型別
- 4、條件變數 pthread_cond_t 型別
- 5、 pthread_cond_t 和 pthread_mutex_t 結合使用
1、pthread_create 函式
1.1 pthread_create 創建新執行緒
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
//引數說明:
// 1)、(傳出引數) 新執行緒ID
// 2)、attr執行緒屬性,NULL表使用默認屬性 pthread_attr_t
// 3)、執行緒主函式:void *(*tfn)(void *)
// 4)、執行緒主函式引數
1.2. 使用例子
pthread_t pthread;
pthread_create(&pthread, NULL,pthread_run, NULL);
// pthread_run 回呼函式
2、pthread_join 函式
1. pthread_join 函式的作用
等待執行緒運行結束退出,一般和pthread_create配對使用
2. pthread_join(&thread, NULL);
3、互斥鎖 pthread_mutex_t 型別
- pthread_mutex_t 型別的初始化,分為動態和靜態兩種
// 動態:
pthread_mutex_t lock;
pthread_mutex_init(&lock, NULL);
// 靜態:
pthead_mutex_t muetx = PTHREAD_MUTEX_INITIALIZER;
2. 銷毀:pthread_mutex_destroy(&lock);
3. 加鎖:pthread_mutex_lock(&lock);
4. 解鎖:pthread_mutex_unlock(&lock);
5. 非阻塞加鎖:pthread_mutex_trylock(&lock);
4、條件變數 pthread_cond_t 型別
- pthread_cond_t 型別的初始化,分為動態和靜態兩種
// 動態:pthread_cond_t
// int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
pthread_cond_t cond;
pthread_cond_init(&cond,NULL);
// 靜態:
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
- 退后用完需要銷毀
pthread_cond_destroy (&cond);
5、 pthread_cond_t 和 pthread_mutex_t 結合使用
- pthread_cond_wait
int pthread_cond_wait(pthread_cond_t * cond, pthread_mutex_t * mutex);
pthread_cond_wait 是阻塞等待函式,它的內部結構是:
首先 pthread_cond_wait前要先加鎖,其次pthread_cond_wait內部會解鎖,然后等待條件變數被其它執行緒激活,最后pthread_cond_wait被激活后會再自動加鎖
- pthread_cond_timedwait
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);
// 作用:其中計時等待方式如果在給定時刻前條件沒有滿足,則回傳ETIMEOUT,結束等待
// 例子:
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_nsec += 100*1000*1000;
ts.tv_sec += ts.tv_nsec / 1000000000;
ts.tv_nsec %= 1000000000;
pthread_cond_timedwait(&cond, & lock, &ts);
- pthread_cond_signal函式
作用:喚醒(至少)一個阻塞在條件變數上的執行緒
使用例子:pthread_cond_signal(&cond);
- pthread_cond_broadcast
喚醒全部阻塞在條件變數上的執行緒 - pthread_cond_wait 的常用套路
// 等待執行緒:
pthread _mutex_lock(&mutex)
while或if(執行緒執行的條件是否成立)
pthread_cond_wait(&cond, &mutex);
// 執行緒執行
pthread_mutex_unlock(&mutex);
// 激活執行緒:
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/255977.html
標籤:其他
上一篇:火鳥門戶系統 5.7 正式版
下一篇:滿足低調之心---playing
