iOS之多執行緒程式設計 三個層次執行緒應用

2021-06-09 00:00:12 字數 2510 閱讀 6102

ios支援三個層次的執行緒程式設計,從底層到高層(層次越高使用越方便,越簡潔)分別是:

1:thread;

2:cocoa operations;

3:grand central dispatch;

簡介:

thread是抽象層次最低的,另外兩種執行緒應用給予thread進行了封裝,對於程式設計師而言,thread相對麻煩,需要程式設計師管理執行緒週期,但是效率最高。thread包含兩種:

cocoa threads——使用nsthread 或直接從 nsobject 的類方法 performselectorinbackground:withobject: 來建立乙個執行緒;

posix threads: 基於 c 語言的乙個多執行緒庫。

建立nsthread的方式有三種:

一:[nsthread detachnewthreadselector:@selector(mythreadmethod:) totarget:self withobject:nil]; 呼叫立即建立乙個新執行緒執行操作

二:nsthread* mythread = [[nsthread alloc] initwithtarget:self

selector:@selector(mythreadmethod:)

object:nil];[mythread start];     

nsthread初始化之後,新的執行緒並沒有執行,而是呼叫 start 時才會建立執行緒執行。這種方法相對上面的方法更加靈活,在啟動新的執行緒之前,對執行緒進行相應的操作,比如設定優先順序,加鎖。

三:[myobj performselectorinbackground:@selector(mythreadmainmethod) withobject:nil];         

利用 nsobject 的類方法 performselectorinbackground:withobject: 來建立乙個執行緒:

以上都可以在新的執行緒中呼叫performselectoronmainthread

: withobject:waituntildone:更新ui,因為子執行緒不能直接更新ui。

執行緒同步與鎖:

有很多時候多個執行緒之間會訪問相同的資料,如何避免a執行緒和b執行緒之間的衝突,以及執行順序等需要程式設計師考慮,這個時候需要用到nscondition,nslock,確保執行緒(原子操作)安全。

用nscodition同步執行的順序

,nscodition 是一種特殊型別的鎖,我們可以用它來同步操作執行的順序。它與 mutex 的區別在於更加精準,等待某個 nscondtion 的執行緒一直被 lock,直到其他執行緒給那個 condition 傳送了訊號。下面我們來看使用示例:

tickets = 100;  

count = 0;  

ticketcondition = [[nscondition alloc] init];  // 鎖物件 

ticketsthreadone = [[nsthread alloc] initwithtarget:self selector:@selector(run) object:nil];  

[ticketsthreadone setname:@"thread-1"];  

[ticketsthreadone start];    

ticketsthreadtwo = [[nsthread alloc] initwithtarget:self selector:@selector(run) object:nil];  

[ticketsthreadtwo setname:@"thread-2"];  

[ticketsthreadtwo start];  

[window makekeyandvisible];   

}  - (void)run else   

[ticketscondition unlock];  

}  }  

執行緒間通訊,互動

在應用程式主線程中做事情:

performselectoronmainthread:withobject:waituntildone:

performselectoronmainthread:withobject:waituntildone:modes:

在指定執行緒中做事情:

performselector:onthread:withobject:waituntildone:

performselector:onthread:withobject:waituntildone:modes:

在當前執行緒中做事情:

performselector:withobject:afterdelay:

performselector:withobject:afterdelay:inmodes:

取消傳送給當前執行緒的某個訊息

cancelpreviousperformrequestswithtarget:

cancelpreviousperformrequestswithtarget:selector:object:

cocoa operetions

iOS之多執行緒程式設計 三個層次執行緒應用

ios支援三個層次的執行緒程式設計,從底層到高層 層次越高使用越方便,越簡潔 分別是 1 thread 2 cocoa operations 3 grand central dispatch 簡介 thread是抽象層次最低的,另外兩種執行緒應用給予thread進行了封裝,對於程式設計師而言,thr...

C 之多執行緒程式設計

一.程序與執行緒 程序 process 是對一段靜態指令序列 程式 的動態執行過程,是系統進行資源分配和排程的乙個基本單位。與程序相關的資訊 包括程序的使用者標識,正在執行的已經編譯好的程式,程序程式和資料在儲存器中的位置等。同乙個程序又可以劃分為若干個獨立的執行流,我們稱之為執行緒 thread ...

Python多執行緒程式設計之多執行緒加鎖

python語言本身是支援多執行緒的,不像php語言。下面的例子是多個執行緒做同一批任務,任務總是有task num個,每次執行緒做乙個任務 print 做完後繼續取任務,直到所有任務完成為止。1 coding utf 8 2import threading 34 start task 0 5 ta...