在很多操作系統上都會用到的API,可移植性特別強。基於C語言框架,在開發過程中極少用到。在很多面試中對該線程使用都很少提及。
那麼好,我們言歸正傳,以代碼的形式給大家講解用法和注意事項。
——————
思路:
在界面上安排一個按鈕,當點擊按鈕時,執行 pThread 多線程;
代碼演示:
1:創建項目;
2:在ViewController裏面添加按鈕,代碼如下:
//第一種方式 pThread
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(40, 100, 100, 40);
[btn setTitle:@"pThread" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor blueColor]];
[btn addTarget:self action:@selector(click_pThread) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
3:實現 click_pThread 事件
- (void)click_pThread {
// [self isMainThread];
NSLog(@"我在主線程中執行");
pthread_t queue;
// pthread_create : 創建任務的方法,
/*
第一個參數:pthread指針
第二個參數:可爲空;
第三個參數:要在子線程中執行的代碼
第四個參數:可爲空;
*/
pthread_create(&queue, NULL, run_pThread, NULL);
}
4:定義 run_pThread 方法
// C 語言 函數定義方式
void *run_pThread(void *data) {
NSLog(@"我在子線程中執行");
//一個模擬任務的執行
for (int i = 0; i < 10 ; i ++) {
sleep(1);
NSLog(@"%d",i);
}
return NULL;
}