常用的多线程

2020-11-17  本文已影响0人  你飞跃俊杰

一、异步处理,返回主线程
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 处理耗时操作的代码块...
//通知主线程刷新
dispatch_async(dispatch_get_main_queue(), ^{
//回调或者说是通知主线程刷新,
});
});

二、队列操作
暂停恢复,先处理A异步,再处理B,然后处理C
dispatch_queue_t myqueue = dispatch_queue_create("queue1", NULL);

dispatch_async(myqueue, ^{
    dispatch_suspend(myqueue);
    }
    
    dispatch_resume(myqueue);
});

dispatch_async(myqueue, ^{
    dispatch_suspend(myqueue);
    }
    
    dispatch_resume(myqueue);
});

三、信号量
处理异步任务的最终同步,ABCD任务处理完再处理其他任务
__block NSInteger number = 0;

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_t group = dispatch_group_create();

//A耗时操作
dispatch_group_enter(group);
NSLog(@"A-");
dispatch_group_async(group, queue, ^{
    number += 2222;
    dispatch_group_leave(group);
    NSLog(@"A+");
});

//B网络请求
dispatch_group_enter(group);
NSLog(@"B-");
dispatch_group_async(group, queue, ^{
[self sendRequestWithCompletion:^(id response) {
    number += [response integerValue];
    dispatch_group_leave(group);
    NSLog(@"B+");
}];
    });

//C网络请求
dispatch_group_enter(group);
NSLog(@"C-");
dispatch_group_async(group, queue, ^{
    [self sendRequestWithCompletion:^(id response) {
        number += [response integerValue];
        dispatch_group_leave(group);
        NSLog(@"C+");
    }];
});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"%zd", number);
});
上一篇 下一篇

猜你喜欢

热点阅读