2011-11-13

Objective-C 多執行緒 ( NSOperationQueue )

objc 的 NSOperationQueue 跟 Thread Pool 很類似,用起來也非常的容易,這邊把 Operation 看成 Thread Task , Operation Queue 則看成 Thread Pool 。
底下舉一個簡單的例子:主執行緒使用另一個執行緒印出 “i am taskClass” 字串
//taskClass 負責印出 “i am taskClass” 字串 
@interface taskClass : NSOperation {
}
//main 繼承於 NSOperation, 執行緒啟動時將執行這個函數
-(void) main;
@end


 
@implementation taskClass
-(void) main
{
    NSAutoreleasePool* nsap =[NSAutoreleasePool new];
    NSLog(@"i am taskClass");
    [nsap drain];
}
@end



//主程式
int main (int argc, const char * argv[])
{
    NSAutoreleasePool* nsap =[NSAutoreleasePool new];

    //建立 NSOperationQueue
    NSOperationQueue* nsoq =[NSOperationQueue new];

    //設定最多同時執行的執行緒數
    [nsoq setMaxConcurrentOperationCount:10];

    //建立 taskClass
    taskClass* myTaskClass =[taskClass new];

    //將 taskClass 丟給 NSOperationQueue
    //NSOperationQueue 會分配執行緒去執行 taskClass 的 main 函數

    [nsoq addOperation:myTaskClass];

    //等待 Queue 裡所有的 Operation 執行完畢
    [nsoq waitUntilAllOperationsAreFinished];
   
    [myTaskClass release];
   
    [nsoq release];
   
    [nsap drain];
}
此外,假如 Operation 執行的程式屬於無限迴圈,則在主程式要結束時,可用 cancelAllOperations 函數來通知 Queue 裡的 Operation 中斷迴圈並結束程式,舉例如下:
@interface taskClass : NSOperation {
}
-(void) main;
@end


@implementation taskClass
-(void) main
{
    //檢查 Cancelled 是否為 true, 否則繼續執行
    while ([self isCancelled]==false) {
        //迴圈工作... 
    }
}
@end


//主程式
int main (int argc, const char * argv[])
{
    NSAutoreleasePool* nsap =[NSAutoreleasePool new];

    NSOperationQueue* nsoq =[NSOperationQueue new];
    [nsoq setMaxConcurrentOperationCount:10]; 

    taskClass* myTaskClass =[taskClass new]; 
    [nsoq addOperation:myTaskClass];


    //通知所有執行中的 Operation 中斷執行
    [nsoq cancelAllOperations]; 

    [nsoq waitUntilAllOperationsAreFinished];

    [myTaskClass release];

    [nsoq release];

    [nsap drain];
}

1 則留言 :

  1. As lengthy as the positioning you select to play on is a legitimate and controlled on-line on line casino. I scrolled method down to} the underside of the slots web page at certainly one of my favorite on-line casinos. Once there, I decided to choose 우리카지노 a slot machine I had by no means seen before. If that is your first time on our website, these related articles will assist you to playing in} slots on-line. Picking a great slot machine to play, you will improve your probabilities. I may also give you some precious slots tips about the best progressive slots to play and how choosing a jackpot recreation can have an effect on} your possibilities of winning.

    回覆刪除