多线程(未完待续)

来源:互联网 发布:淘宝网厂家直销马蜂 编辑:程序博客网 时间:2024/05/16 01:42

当两个或两个以上的任务同时执行时就发生了并发。GCD是一个与block object产生工作的低级的C API。GCD真正的用途是将任务分配到多个核心又不让程序员担心哪个内核执行哪个任务。

GCD的核心是分派队列。GCD为运行任务提供了几个选择:同步执行,异步执行 和 延迟执行。GCD中的所有方法和数据类型都是以dispatch_关键字开头。

dispatch_async  允许你的一个队列上分派任务来异步执行。

dispatch_after    允许你在一个给定的延迟之后运行一个block。

传统上,程序员必须创建自己的线程来并行执行任务。

举一个替代的例子

   在appdelegate里

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    [NSThreaddetachNewThreadSelector:@selector(calculationThreadEntry)toTarget:selfwithObject:nil];

    self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]]autorelease];

    // Override point for customization after application launch.

    self.viewController = [[[ViewControlleralloc] initWithNibName:@"ViewController"bundle:nil]autorelease];

    self.window.rootViewController =self.viewController;

    [self.windowmakeKeyAndVisible];

    return YES;

}

-(void)doCalculation{

   NSLog(@"123");

}

-(void)calculationThreadEntry{

    @autoreleasepool {

       NSUInteger counter = 0;

        while ([[NSThreadcurrentThread]isCancelled] ==NO) {

            [selfdoCalculation];

            counter ++;

           if (counter >= 1000) {

               break;

            }

        }

    }

}

用线程写:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    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_t iteration){

            NSLog(@"123");

        });

    });

    self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]]autorelease];

    self.viewController = [[[ViewControlleralloc] initWithNibName:@"ViewController"bundle:nil]autorelease];

    self.window.rootViewController =self.viewController;

    [self.windowmakeKeyAndVisible];

    return YES;

}


得到的想过一样的。但从代码上来看,还是GCD更实用些。

GCD的三种分派队列:

Main Queue :这个队列在主线程上执行它的所有任务。使用  dispatch_get_main_queue  函数检索到主队列的句柄。

Concurrent Queues :为了执行异步和同步任务,你可以在GCD中检索到这些队列。多个并发队列能够轻而易举的并行执行多个任务,没有更多的线程管理。使用 dispatch_get_global_queue 函数检索一个并发队列句柄。

Serial Queues: 无论你提交同步或者异步任务,这些队列按照先入先出(FIFO)的原则来执行。使用dispatch_queue_create 函数创建一个串行队列,使用完必须使用dispatch_release函数来释放它。


原创粉丝点击