天天看點

多線程之NSThread iOS多線程之pthread、NSThread 1. pthread 2. NSThread

iOS多線程之pthread、NSThread

1. pthread

pthread簡單介紹下,pthread是一套通用的多線程的API,可以在Unix / Linux / Windows 等系統跨平台使用,使用C語言編寫,需要程式員自己管理線程的生命周期,使用難度較大,是以我們在iOS開發中幾乎不使用pthread,簡單了解下就可以了。

引自 百度百科

POSIX線程(POSIX threads),簡稱Pthreads,是線程的POSIX标準。該标準定義了建立和操縱線程的一整套API。在類Unix作業系統(Unix、Linux、Mac OS X等)中,都使用Pthreads作為作業系統的線程。Windows作業系統也有其移植版pthreads-win32。

引自 維基百科

POSIX線程(英語:POSIX Threads,常被縮寫為Pthreads)是POSIX的線程标準,定義了建立和操縱線程的一套API。

實作POSIX 線程标準的庫常被稱作Pthreads,一般用于Unix-like POSIX 系統,如Linux、Solaris。但是Microsoft Windows上的實作也存在,例如直接使用Windows API實作的第三方庫pthreads-w32;而利用Windows的SFU/SUA子系統,則可以使用微軟提供的一部分原生POSIX API。

1.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對應函數裡是需要在新線程中執行的任務)

2. NSThread

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

[NSThread currentThread]

來顯示目前的程序資訊。

下邊我們說說NSThread如何使用。

1. 建立、啟動線程

  • 先建立線程,再啟動線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];    // 線程一啟動,就會線上程thread中執行self的run方法
           
  • 建立線程後自動啟動線程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self 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. 線程的狀态轉換

當我們建立一條線程

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

,在記憶體中的表現為:

多線程之NSThread iOS多線程之pthread、NSThread 1. pthread 2. NSThread

當調用

[thread start];

後,系統把線程對象放入可排程線程池中,線程對象進入就緒狀态,如下圖所示。

多線程之NSThread iOS多線程之pthread、NSThread 1. pthread 2. NSThread

當然,可排程線程池中,會有其他的線程對象,如下圖所示。在這裡我們隻關心左邊的線程對象。

多線程之NSThread iOS多線程之pthread、NSThread 1. pthread 2. NSThread

下邊我們來看看目前線程的狀态轉換。

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

隻看文字可能不太好了解,具體目前線程對象的狀态變化如下圖所示。

多線程之NSThread iOS多線程之pthread、NSThread 1. pthread 2. NSThread

轉載自:http://www.jianshu.com/p/cbaeea5368b1

繼續閱讀