iOS多線程之 pThread

前面總結(jié)了多線程的基本概念,今天學(xué)習(xí)總結(jié)一下多線程的其中一種實(shí)現(xiàn)方案pThread

一、基本概念

pThread(POSIX threads)是一套純C語言的API,需要程序員自己管理線程的生命周期,適用于多種操作系統(tǒng),可跨平臺(tái),移植性強(qiáng),但使用難度較大,iOS開發(fā)中幾乎不使用。

二、pThread的使用方法

1、引入頭文件#import <pthread.h>
2、創(chuàng)建一個(gè)線程:
#pragma mark - 創(chuàng)建線程
- (void)pThreadMethod {
    NSLog(@"主線程執(zhí)行");
    // 1. 定義一個(gè)pThread
    pthread_t pthread;
    // 2. 創(chuàng)建線程 用runPthread方法執(zhí)行任務(wù)
    pthread_create(&pthread, NULL, runPthread, NULL);
}

#pragma mark - 線程調(diào)用方法執(zhí)行任務(wù)
void *runPthread(void *data) {
    NSLog(@"子線程執(zhí)行");
    for (NSInteger index = 0; index < 10; index ++) {
        NSLog(@"%ld", index);
        // 延遲一秒
        sleep(1);
    }
    return NULL;
}

pthread_create(<#pthread_t _Nullable *restrict _Nonnull#>, <#const pthread_attr_t *restrict _Nullable#>, <#void * _Nullable (* _Nonnull)(void * _Nullable)#>, <#void *restrict _Nullable#>)參數(shù)說明:

  • 第一個(gè)參數(shù)pthread_t * __restrict:指向當(dāng)前新線程的指針;
  • 第二個(gè)參數(shù)const pthread_attr_t * __restrict:設(shè)置線程屬性;
  • 第三個(gè)參數(shù)```void * ()(void *):函數(shù)指針,指向一個(gè)函數(shù)的起始地址,線程開始的回調(diào)函數(shù),里面執(zhí)行耗時(shí)任務(wù)
  • 第四個(gè)參數(shù)回到函數(shù)所用的參數(shù)
3、運(yùn)行結(jié)果:
2019-04-09 23:52:04.618053+0800 Test[1310:40633] 主線程執(zhí)行
2019-04-09 23:52:04.618298+0800 Test[1310:40700] 子線程中執(zhí)行
2019-04-09 23:52:04.618442+0800 Test[1310:40700] 0
2019-04-09 23:52:05.622067+0800 Test[1310:40700] 1
2019-04-09 23:52:06.627134+0800 Test[1310:40700] 2
2019-04-09 23:52:07.627593+0800 Test[1310:40700] 3
2019-04-09 23:52:08.633008+0800 Test[1310:40700] 4

· Test[1310:40633] 主線程執(zhí)行中1310表示當(dāng)前進(jìn)程,40633表示主線程
· Test[1310:40700] 子線程執(zhí)行中1310表示當(dāng)前進(jìn)程,40700表示子線程

三、PThread的其他方法

  • pthread_t:線程ID
  • pthread_attr_t:線程屬性
  • pthread_create():創(chuàng)建一個(gè)線程
  • pthread_exit():終止當(dāng)前進(jìn)程
  • pthread_cancle():中斷另外一個(gè)線程的運(yùn)行
  • pthread_join():阻塞當(dāng)前的進(jìn)程,知道另外一個(gè)進(jìn)程運(yùn)行結(jié)束
  • pthread_attr_init():初始化線程屬性
  • pthread_attr_setdetachstate():設(shè)置脫離狀態(tài)的屬性(決定這個(gè)線程在終止時(shí)是否可以被結(jié)合)
  • pthread_attr_getdetachstate():獲取脫離狀態(tài)的屬性
  • pthread_attr_destroy():刪除線程屬性
  • pthread_kill:向線程發(fā)送信號(hào)
  • pthread_equal():對兩個(gè)線程標(biāo)識(shí)號(hào)進(jìn)行比較
  • pthread_detach():分離線程
  • pthread_self():查詢線程自身線程標(biāo)識(shí)號(hào)

參考地址:

iOS開發(fā) - 多線程實(shí)現(xiàn)方案之Pthread篇

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容