執行緒創建等待及退出
1.Linux上執行緒開發API概要
多執行緒開發在 Linux 平臺上已經有成熟的 pthread 庫支持,其涉及的多執行緒開發的最基本概念主要包含三點:執行緒,互斥鎖,條件,其中,執行緒操作又分執行緒的創建,退出,等待 3 種,互斥鎖則包括 4 種操作,分別是創建,銷毀,加鎖和解鎖,條件操作有 5 種操作:創建,銷毀,觸發,廣播和等待,其他的一些執行緒擴展概念,如信號燈等,都可以通過上面的三個基本元素的基本操作封裝出來,詳細請見下表:

2.與執行緒自身相關API
執行緒創建:
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 回傳:若成功回傳0,否則回傳錯誤編號在這里插入代碼片
當pthread_create成功回傳時,由tidp指向的記憶體單元被設定為新創建執行緒的執行緒ID,attr引數用于定制各種不同的執行緒屬性,暫可以把它設定為NULL,以創建默認屬性的執行緒,
新創建的執行緒從start_rtn函式的地址開始運行,該函式只有一個無型別指標引數arg,如果需要向start_rtn函式傳遞的引數不止一個,那么需要把這些引數放到一個結構中,然后把這個結構的地址作為arg引數傳入,
執行緒退出:
單個執行緒可以通過以下三種方式退出,在不終止整個行程的情況下停止它的控制流:
1)執行緒只是從啟動例程中回傳,回傳值是執行緒的退出碼,
2)執行緒可以被同一行程中的其他執行緒取消,
3)執行緒呼叫pthread_exit:
#include <pthread.h>
int pthread_exit(void *rval_ptr);
rval_ptr是一個無型別指標,與傳給啟動例程的單個引數類似,行程中的其他執行緒可以通過呼叫pthread_join函式訪問到這個指標,
執行緒等待:
#include <pthread.h>
int pthread_join(pthread_t thread, void **rval_ptr);
// 回傳:若成功回傳0,否則回傳錯誤編號
呼叫這個函式的執行緒將一直阻塞,直到指定的執行緒呼叫pthread_exit、從啟動例程中回傳或者被取消,如果例程只是從它的啟動例程回傳i,rval_ptr將包含回傳碼,如果執行緒被取消,由rval_ptr指定的記憶體單元就置為PTHREAD_CANCELED,
可以通過呼叫pthread_join自動把執行緒置于分離狀態,這樣資源就可以恢復,如果執行緒已經處于分離狀態,pthread_join呼叫就會失敗,回傳EINVAL,
如果對執行緒的回傳值不感興趣,可以把rval_ptr置為NULL,在這種情況下,呼叫pthread_join函式將等待指定的執行緒終止,但并不獲得執行緒的終止狀態,
綜合使用例程:
代碼:
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 回傳:若成功回傳0,否則回傳錯誤編號----創建執行緒
void *func1(void*arg)//引數3:呼叫無型別指標API
{
static int ret=10;//使函式結束,記憶體還在
static char *p = "t1 is run out";
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
//pthread_self():回傳自身執行緒id,為pthread_t型別
printf("t1:param is %d:\n",*((int*)arg));//轉化為int*,再取值
//pthread_exit((void *)&ret);
pthread_exit((void *)p);
}
int main()
{
int ret;//回傳值
pthread_t t1;
int param=100;//引數4:呼叫時:將int*轉化為void*.100:隨便給的數
//int *pret=NULL;
char *pret1=NULL;
ret=pthread_create(&t1,NULL,func1,(void*)¶m);
//引數1:指標指向t1,NULL:執行緒屬性,引數3:啟動執行緒呼叫的函式,引數4:列印的值
if(ret==0)
{
printf("main函式創建執行緒t1成功\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
//pthread_join(t1,NULL);//等待執行緒,主執行緒執行完不識訓,等待子執行緒
//pthread_join(t1,(void **)&pret);//等待執行緒,pret不指向null,指向ret
pthread_join(t1,(void **)&pret1);//等待執行緒,pret不指向null,指向ret
//printf("main:t1 quit:%d\n",*pret);
printf("main:t1 quit:%s\n",pret1);
return 0;
}
執行結果:
dazai@dazai:~$ gedit demo1.c
dazai@dazai:~$ gcc demo1.c -lpthread
dazai@dazai:~$ ./a.out
main函式創建執行緒t1成功
t1:-1210954944 thread is create
t1:param is 100:
main:-1210951936
main:t1 quit:t1 is run out
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/19229.html
標籤:其他
