iOS -GCD

来源:互联网 发布:mysql offset 性能 编辑:程序博客网 时间:2024/06/05 20:43

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

//     处理数据,网络请求,

        

        dispatch_async(dispatch_get_main_queue(), ^{

//    在此处刷新UI界面

        });

    });

   

    

    

//    利用GCD延迟执行任务的方法

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

        NSLog(@"1");

    double delayInSeconds=2.0;

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds*NSEC_PER_SEC);

    dispatch_after(popTime,dispatch_get_main_queue(), ^(void){

        // code to be executed on the main queue after delay

        NSLog(@"2");


    });

 });

   

    

//    利用GCD组运行分为并行和串行

//   并行

    dispatch_queue_t queue;

    queue=dispatch_queue_create("MyQueue",NULL);

    dispatch_async(queue, ^{

        printf("Do\n");

    });

    dispatch_async(queue, ^{

        printf("some\n");

    });

    dispatch_async(queue, ^{

        printf("work here.\n");

    });

//  这个先执行 然后再执行上边的输出

    printf("The first block may or may not have run.\n");


    

// 串行

//   先执行Do some more here  然后再执行BOth blocks have completed

    dispatch_sync(queue, ^{

        printf("Do some more work here.\n");

    });

    printf("Both blocks have completed.\n");

    

    

//    并行与串行混编

//   执行task1 task2 task3 都运行完成以后才异步运行 task4 task5 task6 我们该怎么做呢?这里我们可以引入group的概念

    dispatch_queue_t aDQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    dispatch_group_t group =dispatch_group_create();

//    Add a task to the group

    dispatch_group_async(group, aDQueue, ^{

        printf("task 1 \n");

    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 2 \n");

    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 3 \n");

    });

    printf("wait 1 2 3\n");

    

    dispatch_group_wait(group,DISPATCH_TIME_FOREVER);

    printf("task 1 2 3 finished\n");

    

    group=dispatch_group_create();

//    add a task to the group

    dispatch_group_async(group, aDQueue, ^{

        printf("task 4 \n");


    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 5 \n");

    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 6 \n");

    });

    printf("wait 4 5 6 \n");

    dispatch_group_wait(group,DISPATCH_TIME_FOREVER);

    printf("task 4 5 6 finished \n");


0 0