- 一個接口的請求,依賴于另一個請求的結(jié)果
- 使用
GCD
組隊列中的dispatch_group_async
和dispatch_group_notify
- (void)dispatchGroup{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
// 請求1
NSLog(@"11111");
});
dispatch_group_notify(group, queue, ^{
// 請求2
NSLog(@"2222222");
});
}
- 使用
GCD
的柵欄函數(shù)dispatch_barrier_async
- (void)dispatchBarrier{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
// 請求1
NSLog(@"11111");
});
dispatch_barrier_async(queue, ^{
// 請求2
NSLog(@"22222");
});
}
- 使用
GCD
的信號量dispatch_semaphore
京郑,信號量的初始值可以用來控制線程并發(fā)訪問的最大數(shù)量醒陆。如果設(shè)置為1
則為串行執(zhí)行瀑构,達(dá)到線程同步的目的
- (void)dispatchSemaphore{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(queue, ^{
NSLog(@"11111");
// 請求1結(jié)束后 增加信號個數(shù),dispatch_semaphore_signal()信號加1
dispatch_semaphore_signal(semaphore);
});
dispatch_async(queue, ^{
// 無限等待,直到請求1結(jié)束 增加了信號量,大于0后才開始,dispatch_semaphore_wait()信號減1
// 如果信號量的值 > 0,就讓信號量的值減1刨摩,然后繼續(xù)往下執(zhí)行代碼
// 如果信號量的值 <= 0寺晌,就會休眠等待,直到信號量的值變成>0码邻,就讓信號量的值減1折剃,然后繼續(xù)往下執(zhí)行代碼
// DISPATCH_TIME_FOREVER 這個是一直等待的意思
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// 請求2開始
NSLog(@"22222");
});
}
- 在異步線程中
return
一個字符串
- 模擬異步線程方法,需要
return
字符串@"小熊"
- (void)asyncRequestMethod:(void(^)(NSString *name))successBlock{
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
if (successBlock) {
successBlock(@"小熊");
}
});
}
- (NSString *)nameStr{
__block NSString *nameStr = @"小關(guān)";
__block BOOL isSleep = YES;
[self asyncRequestMethod:^(NSString *name) {
nameStr = name;
NSLog(@"1");
isSleep = NO;
NSLog(@"3");
}];
//while循環(huán)等待阻塞線程
while (isSleep) {
NSLog(@"4");
}
NSLog(@"2");
return nameStr;
}
- (NSString *)nameStr{
__block NSString *nameStr = @"小關(guān)";
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self asyncRequestMethod:^(NSString *name) {
nameStr = name;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return nameStr;
}
- 利用
dispatch_group_t
調(diào)度組怕犁,異步改同步
- (NSString *)nameStr{
__block NSString *nameStr = @"小關(guān)";
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self asyncRequestMethod:^(NSString *name) {
nameStr = name;
dispatch_group_leave(group);
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
return nameStr;
}
附:GrandCentralDispatchDemo