天天看點

iOS中多線程的實作方案之pthread和NSThread

【文章結尾附上iOS中多線程的實作方案總結】

一、pthread

a. demo1

iOS中多線程的實作方案之pthread和NSThread

b. demo2

iOS中多線程的實作方案之pthread和NSThread

c. 對demo2中提到的 __bridge 的了解

ARC隻負責OC的代碼,不負責 c 的代碼;

在 ARC 中,使用到和  c  語言對應的資料類型,應該使用 __bridge 橋接,在MRC中,不需要橋接;

在 OC 中,如果是 ARC 的話,編譯的時候會自動添加 retain 、 release 、 autorelease; 如 果  c  語言的架構中,函數名中出現 create 、 retain 、 copy ,需要 release;

橋 接的目的就是解決上述問題。

二、 NSThread

1. 建立線程的3種方式: a. 建立和啟動線程

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

[thread start]; //手動啟動線程;

// 一個NSThread對象就代表一條線程。

// 線程一啟動,就會線上程thread中執行self的run方法。

b. 建立線程後自動啟動線程

[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

c. 隐式建立并啟動線程

[self performSelectorInBackground:@selector(run) withObject:nil];

總結:

b和c建立線程方式的優點:簡單快捷;

b和c建立線程方式的缺點:無法對線程進行更詳細的設定。

2.線程的狀态

a. 建立線程

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

b. 啟動線程;

- (void)start NS_AVAILABLE(10_5, 2_0);

// 進入就緒狀态-> 運作狀态;

// 當線程任務執行完畢,自動進入死亡狀态。

c. 阻塞(暫停)線程

+ (void)sleepUntilDate:(NSDate *)date;

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

// 進入阻塞狀态

// 線程處理阻塞狀态時在記憶體中的表現情況:(線程被移出可排程線程池,此時不可排程)

d. 強制停止線程

+ (void)exit;

// 進入死亡狀态

// 當線程的任務結束,發生異常,或強制退出,這三種情況會導緻線程的死亡。

// 線程死亡後,線程對象從記憶體中移除。

注意:一旦線程停止(死亡)了,就不能再次開啟任務。

一張圖展示線程的狀态:

iOS中多線程的實作方案之pthread和NSThread

3. 常用屬性方法

a. 獲得目前線程

NSThread *current = [NSThreadcurrentThread];

b. 線程的排程優先級

+ (double)threadPriority;

@property double threadPriorityNS_AVAILABLE(10_6, 4_0); 

// 排程優先級的取值範圍是0.0 ~ 1.0,預設0.5,值越大,優先級越高;

// 但優先級高的不一定先運作,可能性更大而已。

c. 線程的名字

@property (nullable,copy) NSString *nameNS_AVAILABLE(10_5, 2_0);

d. 主線程相關用法

+ (NSThread *)mainThread NS_AVAILABLE(10_5, 2_0);

+ (BOOL)isMainThread NS_AVAILABLE(10_5, 2_0); // 是否為主線程

@property (readonly)BOOL isMainThread NS_AVAILABLE(10_5, 2_0);

一張圖總結iOS中多線程的實作方案:

iOS中多線程的實作方案之pthread和NSThread