天天看點

pThread ,NSThread的深入了解

pThread POSIX線程(英語:POSIX Threads,常被縮寫為Pthreads)是POSIX的線程标準,定義了建立和操縱線程的一套API。 pthread是一套通用的多線程的API,可以在Unix / Linux / Windows 等系統跨平台使用,使用C語言編寫,需要程式員自己管理線程的生命周期,使用難度較大。

pThread的使用方法: 1、首先要包含頭檔案#import <pthread.h> 2、其次要建立線程,并開啟線程執行任務

// 建立線程——定義一個pthread_t類型變量 pthread_t thread; // 開啟線程——執行任務 pthread_create(&thread, NULL, run, NULL); void * run(void *param) { // 新線程調用方法,裡邊為需要執行的任務 NSLog(@"%@", [NSThread currentThread]); return NULL; } pthread_create(&thread, NULL, run, NULL) ; 中各項參數含義:

  • 第一個參數&thread是線程對象
  • 第二個和第四個是線程屬性,可複制NULL
  • 第三個run表示指向函數的指針(run對應函數裡是需要在新線程中執行新的任務)

NSThread NSThread是蘋果官方提供的,使用起來比pthread更加面向對象,簡單易用,可以直接操作線程對象。不過也需要需要程式員自己管理線程的生命周期(主要是建立),我們在開發的過程中偶爾使用NSThread。比如我們會經常調用[NSThread currentThread]來顯示目前的程序資訊

1. 建立、啟動線程 先建立線程,再啟動線程// 線程一啟動,就會線上程thread中執行self的run方法 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [thread start];

建立線程後自動啟動線程 [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

隐式建立并啟動線程 [self performSelectorInBackground:@selector(run) withObject:nil];

2、相關用法 // 獲得主線程 + (NSThread *)mainThread; // 判斷是否為主線程(對象方法) - (BOOL)isMainThread; // 判斷是否為主線程(類方法) + (BOOL)isMainThread; // 獲得目前線程 NSThread *current = [NSThread currentThread]; // 線程的名字——setter方法 - (void)setName:(NSString *)n; // 線程的名字——getter方法 - (NSString *)name; 3、線程狀态控制

  • 啟動線程方法

// 線程進入就緒狀态 -> 運作狀态。當線程任務執行完畢,自動進入死亡狀态 - (void)start;

  • 阻塞(暫停)線程方法

// 線程進入阻塞狀态 + (void)sleepUntilDate:(NSDate *)date; + (void)sleepForTimeInterval:(NSTimeInterval)ti;

  • 強制停止線程

// 線程進入死亡狀态 + (void)exit; 4.線程的狀态轉換 如果CPU現在排程目前線程對象,則目前線程對象進入運作狀态,如果CPU排程其他線程對象,則目前線程對象回到就緒狀态。 如果CPU在運作目前線程對象的時候調用了sleep方法\等待同步鎖,則目前線程對象就進入了阻塞狀态,等到sleep到時\得到同步鎖,則回到就緒狀态。 如果CPU在運作目前線程對象的時候線程任務執行完畢\異常強制退出,則目前線程對象進入死亡狀态。