上一節中,我們探究了OC中重要的實現多線程的方法——NSOperation。本節中,我們了解一下不常用的一種創建多線程的方式——pThread。
相關鏈接:
NSOpreation鏈接:iOS詳解多線程(實現篇——NSOperation)
GCD鏈接:iOS詳解多線程(實現篇——GCD)
NSThread鏈接:詳解多線程(實現篇——NSThread)
多線程概念篇鏈接:詳解多線程(概念篇——進程、線程以及多線程原理)
源碼鏈接:https://github.com/weiman152/Multithreading.git
多線程的實現方法
1.NSThread(OC)
2.GCD(C語言)
3.NSOperation(OC)
4.C語言的pthread(C語言)
5.其他實現多線程方法
本節主要內容:
1.pThread是什么
2.pThread如何使用
1.pThread是什么
pThread并不是OC特有的實現多線程的方法,而是Unix、Linux還有Windows都通用的一種實現多線程的方式。
pThread的全稱是POSIX threads,是線程的 POSIX 標準。
pThread是C語言的,在iOS的開發中極少使用。
2.pThread如何使用
2.1 創建一個線程,并執行任務
使用之前,記得先導入頭文件
#import <pthread.h>
//新線程調用方法,內容為要執行的任務
void * run(void * param){
NSLog(@"任務執行,線程:%@", [NSThread currentThread]);
return NULL;
}
- (IBAction)test1:(id)sender {
//1. 創建線程,定義一個pthread_t類型的變量
pthread_t thread;
//2. 開啟線程,執行任務
pthread_create(&thread, NULL, run, NULL);
//3. 設置子線程的狀態設置為 detached,該線程運行結束后會自動釋放所有資源
pthread_detach(thread);
}
運行結果:
從結果可以看出,開啟了新的線程,執行任務。
2.2 pThread的其他方法
pthread_create() 創建一個線程
pthread_exit() 終止當前線程
pthread_cancel() 中斷另外一個線程的運行
pthread_join() 阻塞當前的線程,直到另外一個線程運行結束
pthread_attr_init() 初始化線程的屬性
pthread_attr_setdetachstate() 設置脫離狀態的屬性(決定這個線程在終止時是否可以被結合)
pthread_attr_getdetachstate() 獲取脫離狀態的屬性
pthread_attr_destroy() 刪除線程的屬性
pthread_kill() 向線程發送一個信號
由于pThread我們基本用不到,所以不再做深入研究。