iOS-多線程之pthread

pthread簡介

pthread是POSIX thread的簡寫,一套通用的多線程API,適用於Unix、Linux、Windows等系統,跨平臺、可移植,使用難度大,C語言框架,線程生命週期由程序員管理。

方法列表

方法名 解釋
pthread_create() 創建一個線程
pthread_exit() 終止當前線程
pthread_cancel() 中斷另外一個線程的運行
pthread_join() 阻塞當前的線程,直到另外一個線程運行結束
pthread_attr_init() 初始化線程的屬性
pthread_attr_setdetachstate() 設置脫離狀態的屬性(決定這個線程在終止時是否可以被結合)
pthread_attr_getdetachstate() 獲取脫離狀態的屬性
pthread_attr_destroy() 刪除線程的屬性
pthread_kill() 向線程發送一個信號

使用

包含頭文件#import <pthread.h>

- (void)test{
    //創建線程 定義一個pthread_t類型變量
    pthread_t thread;
    //開啓線程執行任務
    //第一個參數&thread是線程對象,指向線程標識符的指針
	//第二個是線程屬性,可賦值NULL
	//第三個run表示指向函數的指針(run對應函數裏是需要在新線程中執行的任務)
	//第四個是運行函數的參數,可賦值NULL
    pthread_create(&thread,NULL,run,NULL);
    //設置子線程的狀態設置爲 detached,該線程運行結束後會自動釋放所有資源
    pthread_detach(thread);
}

//新線程調用方法,裏邊爲需要執行的任務
void * run(void *param){
    NSLog(@"%@", [NSThread currentThread]);
    return NULL;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章