iOS并发处理的那些事(译自外文)

来源:互联网 发布:pkpm是什么软件 编辑:程序博客网 时间:2024/04/28 13:56
 
  • -  (void) doCalculation{

    /* Do your calculation here */

    }

  • -  (void) calculationThreadEntry{

    @autoreleasepool {
    NSUInteger counter = 0;
    while ([[NSThread currentThread] isCancelled] == NO){

    [self doCalculation];counter++;
    if (counter >= 1000){

    break;}

    }}

    }

  • -  (BOOL) application:(UIApplication *)application

    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    /* Start the thread */


  • //这里用NSThread生成一个新的线程,calculationThreadEntry这个方法,在新的线程中执行。

  • //其中这里需要注意的一点就是,calculationThreadEntry中得操作要放在自动释放池中进行。


  • [NSThread detachNewThreadSelector:@selector(calculationThreadEntry)

    toTarget:selfwithObject:nil];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    return YES;

  • }


而如果我们要用GCD做同样的工作,则不用显得如此繁琐

dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

        size_t numberOfIterations=1000;

       dispatch_async(queue, ^(void){dispatch_apply(numberOfIterations, queue,^(size_titeration){

  1. /* Perform the operation here */

});});

妹的,csdn太难用了

原创粉丝点击