02 多線程——Pthread

多線程——Pthread

前言

Pthread線程 (POSIX threads),簡(jiǎn)稱Pthreads,是線程的POSIX標(biāo)準(zhǔn)。該標(biāo)準(zhǔn)定義了創(chuàng)建和操作線程的一整套API,在類Unix操作系統(tǒng)(Unix、Linux、Max OS X)中,都使用Pthreads作為操作系統(tǒng)的線程。連Windows操作系統(tǒng)也有它的移植版pthreads-win32。
Pthread定義了一套C語(yǔ)言的類型、函數(shù)與常量,它以Pthread.h頭文件和一個(gè)線程庫(kù)實(shí)現(xiàn)。

數(shù)據(jù)類型

 pthread_t //線程ID
 pthread_attr_t //線程屬性

操縱函數(shù)

pthread_create() //創(chuàng)建一個(gè)線程
pthread_exit() //終止當(dāng)前線程
pthread_cancel() //中斷另外一個(gè)線程的運(yùn)行
pthread_join()  //阻塞當(dāng)前的線程,直到另外一個(gè)線程運(yùn)行結(jié)束
pthread_attr_init() //初始化線程的屬性
pthread_attr_setdetachstate() //設(shè)置脫離狀態(tài)的屬性
pthread_attr_getdetachstate()  //獲取脫離狀態(tài)的屬性
pthread_attr_destory() //刪除線程的屬性
pthread_kill() //向線程發(fā)送一個(gè)信號(hào)

同步函數(shù)

用于mutex 和 條件變量

pthread_mutex_init() //初始化互斥鎖
pthread_mutex_destory() //刪除互斥鎖
pthread_mutex_lock() //占有互斥鎖(阻塞操縱)
pthread_mutex_trylock() //試圖占有互斥鎖
pthread_mutex_unlock() //釋放互斥鎖
pthread_cond_init() //初始化條件變量
pthread_cond_destory() //銷毀條件變量
pthread_cond_signal() //喚醒第一個(gè)調(diào)用等待而進(jìn)入睡眠的線程
pthread_cond_wait() //等待條件變量的特殊條件發(fā)生
pthread_attr_getschdparam()//獲取線程優(yōu)先級(jí)
pthread_attr_setschedparam() //設(shè)置線程優(yōu)先級(jí)

pthread iOS示例代碼

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self pthreadDemo];
}

-(void)pthreadDemo{
    
    /**
     pthread 是屬于 POSIX 多線程開(kāi)發(fā)框架
     
     參數(shù):
     1.指向線程代號(hào)的指針
     2.線程的屬性
     3.指向函數(shù)的指針
     4.傳遞給該函數(shù)的參數(shù)
     
     返回值
     - 如果是0,標(biāo)示正確
     - 如果非0,標(biāo)示錯(cuò)誤代碼
     
     void *   (*)      (void *)
     返回值   (函數(shù)指針)  (參數(shù))
     void *  和OC中的  id 是等價(jià)的!
     
     
     */
    NSString * str = @"hello Miss CC";
    pthread_t threadId;
    /**
     - 在 ARC 開(kāi)發(fā)中,如果涉及到和C語(yǔ)言中的相同的數(shù)據(jù)類型進(jìn)行轉(zhuǎn)換,需要使用 __bridge "橋接"
     - 在 MRC 不需要
     */
    
    int result = pthread_create(&threadId, NULL, &demo, (__bridge  void *)(str));
   
    if (result == 0) {
        NSLog(@"OK");
    }else{
        NSLog(@"error %d",result);
    }
    
    
    
}

void * demo(void * param){
    NSLog(@"%@ %@",[NSThread currentThread],param);
    
    return NULL;
}

小結(jié)

  • C語(yǔ)言中的 void * 等價(jià)于 OC 中的id指針
  • 在混合開(kāi)發(fā)中,C與OC之間數(shù)據(jù)傳遞,需要使用__bridge進(jìn)行橋接。在C語(yǔ)言環(huán)境需要自行內(nèi)存管理。
  • pthread 在iOS項(xiàng)目中使用的非常少見(jiàn)。

小伙伴們閱讀后,請(qǐng)喜歡一下。文章更新可以提醒到你哦~~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容