iOS 多執行緒 NSThread

2021-06-03 13:55:22 字數 2255 閱讀 9459

- (ibaction) startthreadbuttonpressed:(uibutton *)sender

建立新的執行緒,執行緒的函式為 startthebackgroundjob.

具體的 startthebackgroundjob 函式定義如下.

- (void)startthebackgroundjob

在第1行,建立了乙個 nsautoreleasepool 物件,用來管理執行緒中自動釋放的物件資源。

最後一行,阻塞呼叫(waituntildone狀態是on)函式 makemyprogressbarmoving。

- (void)makemyprogressbarmoving

執行緒的堆疊大小

iphone裝置上的應用程式開發也是屬於嵌入式裝置的開發,同樣需要注意嵌入式裝置開發時的幾點問題,比如資源上限,處理器速度等。

你可以用下面的例子測試你的裝置,這裡使用posix thread(pthread),裝置環境是 iphone 3gs(16gb)、sdk是3.1.3。

#include "pthread.h"

void *threadfunc(void *arg)

void* stack_base = pthread_get_stackaddr_np(pthread_self());

size_t stack_size = pthread_get_stacksize_np(pthread_self());

struct rlimit limit;

getrlimit(rlimit_stack, &limit);

nslog(@"main thread: base:%p / size:%u", stack_base, stack_size);

nslog(@" rlimit-> soft:%llu / hard:%llu", limit.rlim_cur, limit.rlim_max);

pthread_t thread;

pthread_create(&thread, null, threadfunc, null);

[window addsubview:viewcontroller.view];

[window makekeyandvisible];

}

結果如下:

模擬器

main thread: base:0xc0000000 / size:524288

rlimit-> soft:8388608 / hard:67104768

thread: base:0xb014b000 / size:524288

裝置

main thread: base:0x30000000 / size:524288

rlimit-> soft:1044480 / hard:1044480

thread: base:0xf1000 / size:524288

由此可見,當你測試多執行緒的程式時,模擬器和實際裝置的堆疊大小是不一樣的。如果有大量遞迴函式呼叫可要注意了。

autorelease

nsautoreleasenopool(): object 0x********* of class nsconretedata autoreleased with no pool in place ….

nsautoreleasepool *pool = [[nsautoreleasepool alloc]init];

子執行緒中描畫視窗

多執行緒程式設計中普遍遵循乙個原則,就是一切與ui相關的操作都有主線程做,子執行緒只負責事務,資料方面的處理。那麼如果想在子執行緒中更新ui時怎麼做呢?如果是在windows下,你會 postmessage 乙個描畫更新的訊息,在iphone中,需要使用performselectoronmainthread 委託主線程處理。

imageview.image = [uiimage imagenamed:@"hoge.png"];

這麼做,什麼也不會出現的。需要將該處理委託給主線程來做,像下面:

[delegate performselectoronmainthread:@selector(theprocess:) withobject:nil waituntildone:yes];

就ok了!

iOS 多執行緒 NSThread

nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start nsthread mainthread 獲得主線程 bool ismainthread 是否為主執行緒 b...

iOS 多執行緒 NSThread

nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start 複製 上述2種建立執行緒方式的優缺點 void sleepuntildate nsdate date vo...

iOS多執行緒之NSThread

ios多執行緒之nsthread 乙個nsthread物件就代表一條執行緒 1.建立,啟動執行緒 nsthread thread nsthread alloc initwithtarget self selector selector run object nil thread start 主線程相...