Grand Central Dispatch vs. NSThread

前端 未结 3 1574
孤独总比滥情好
孤独总比滥情好 2020-12-13 04:52

I created some test code for NSThread and Grand Central Dispatch (GCD):

- (void)doIt:(NSNumber *)i
{
 sleep(1);
 NSLog(@\"Thread#%i\", [i intValue]);
}

- (I         


        
3条回答
  •  [愿得一人]
    2020-12-13 05:32

    If anyone want to test, which method is the best for the spedify probleme, here ist the code:

    #define MAX_COUNT 99999999
    #define HOW_MUCH 10
    - (void)doIt:(NSNumber *)i
    {
        for (int j = 0; j < MAX_COUNT; j++)
            ;
        NSLog(@"Thread#%i", [i intValue]);
    }
    
    
    - (IBAction)doWork:(id)sender
    {
        NSLog(@"START");
    
        for (int i = 0; i < HOW_MUCH; i++) {
            NSNumber *t = [NSNumber numberWithInt:i];
            [NSThread detachNewThreadSelector:@selector(doIt:) toTarget:self withObject:t];
        }
    
        sleep(3);
    
    
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_apply(HOW_MUCH, queue, ^(size_t i) {
            for (int j = 0; j < MAX_COUNT; j++)
                ;
            NSLog(@"GCD APPLY %u",(int)i);
        });
    
    
        sleep(3);
    
        for (size_t k = 0; k < HOW_MUCH; k++) {
            dispatch_async(queue, ^(void) {
                for (int j = 0; j < MAX_COUNT; j++)
                    ;
                NSLog(@"GCD ASYNC#%u",(int)k);
            });
        }
    
        sleep(10);
        NSLog(@"DONE");
    }
    

提交回复
热议问题