原型:? ?
? ? ? ? #include? ? <pthread.h>
? ? ? ? int pthread_eaual(pthread_t tid1,pthread_t tid2);? //判斷兩個(gè)線程ID是否相等
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?相等返回非0掏导,不相等返回0.
? ? ? ? #include? ? <pthread.h>
? ? ? ? pthread_t pthread_self(void);? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //獲取自身線程ID
? ? ? ? 線程創(chuàng)建
? ? ? ? #include? ? <pthread.h>
? ? ? ? int? ? pthread_creat(pthread_t *restrict tidp,????const pthread_attr_t *attr,????void*(*start_rtn)(void),????void? ? *restrict arg);? ? ? ? //創(chuàng)建線程
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?成功返回0挺尿,否則返回錯(cuò)誤編號
? ? ? ? tidp:指向的內(nèi)存單元被設(shè)置為新創(chuàng)建的現(xiàn)成的線程ID
? ? ? ? attr:用于定制線程的線程屬性渊抄,設(shè)置為NULL時(shí)抗愁,則使用默認(rèn)屬性缀遍。
? ? ? ? 新創(chuàng)建的函數(shù)從strat_rtn函數(shù)的地址開始運(yùn)行醒串,該函數(shù)只有一個(gè)無類型指針參數(shù)arg. 若想向strat_rtn傳遞不止一個(gè)參數(shù)帖鸦,可以將多個(gè)參數(shù)放在一個(gè)結(jié)構(gòu)體中易遣,然后把結(jié)構(gòu)體的地址作為arg參數(shù)傳入咱筛。
? ? ? ? 線程終止
? ? ? ? ? ? ? ? 如果進(jìn)程中的任一線程調(diào)用了exit, _Exit或_exit,則整個(gè)進(jìn)程會(huì)終止搓幌。同樣,如果信號的默認(rèn)動(dòng)作是終止進(jìn)程迅箩,那么溉愁,把信號發(fā)送到進(jìn)程會(huì)終止整個(gè)進(jìn)程。
? ? ? ? ? ? ? ? 單個(gè)進(jìn)程的退出方式有三種:
? ? ? ? ? ? ? ? 1.線程只是從啟動(dòng)的例程中退出饲趋,返回值是線程的終止碼拐揭。????
? ? ? ? ? ? ? ? 2.線程可以被統(tǒng)一進(jìn)程中的其他線程取消撤蟆。
? ? ? ? ? ? ? ? 3.線程調(diào)用 pthread_exit;
? ? ? ? ? ? #include? ? <pthread.h>
? ? ? ? ? ? void? ? pthread_join(pthread_t? ? thread, void? ? **rval_ptr);? ? ? ? //成功返回0,否則返回錯(cuò)誤編號堂污。
? ? ? ? ? ? pthread_join()函數(shù)家肯,以阻塞的方式等待thread指定的線程調(diào)用pthread_exit、重新啟動(dòng)例程中返回
? ??????????如果線程已經(jīng)結(jié)束盟猖,那么該函數(shù)會(huì)立即返回讨衣。并且thread指定的線程必須是joinable的。
????????????thread: 線程標(biāo)識(shí)符式镐,即線程ID反镇,標(biāo)識(shí)唯一線程。rval_ptr: 用戶定義的指針碟案,用來存儲(chǔ)被等待線程的返回值愿险。
????????????如果線程是從啟動(dòng)例程中返回,
????????????rval_ptr將包含返回碼价说,如果線程被取消辆亏,由rval_ptr指向的內(nèi)存單元被置為PTHREAD_CANCELED。
?
? ??????線程同步
????????????????線程同步機(jī)制包括互斥鳖目,讀寫鎖以及條件變量
? ??????互斥
????????????????可以把互斥變量之置為常量PTHREAD_MUTEX_INITIALIZER(針對靜態(tài)分配的互斥量)扮叨,或調(diào)用pthread_mutex_init函數(shù)進(jìn)行初始化。如果動(dòng)態(tài)的分配互斥量(如調(diào)用malloc函數(shù))领迈,那么在釋放內(nèi)存前需要調(diào)用pthread_mutex_destory彻磁。
? ? ? ? ? ? ? ? #include? ? <pthread.h>
? ? ? ? ? ? ? ? int pthread_mutex_init(pthread_mutex_t? ? *restrict mutex,? ? const? ? pthread_mutexattr_t? ? *restrict? ? attr);
? ? ? ? ? ? ? ? int? ? pthread_mutex_destory(pthread_mutex_t? ? mutex);
? ? ? ? ? ? ? ? int? ? ?pthread_mutex_lock(pthread_mutex_t *mutex);