1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
// 网络请求模拟 - (void)httpRequest:(NSString *)method param:(NSDictionary *)param completion:(void(^)(id response))block { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSString *command = [param objectForKey:@"commandKey"]; NSLog(@"request: %@ run in thread: %@", command, [NSThread currentThread]); NSTimeInterval sleepInterval = arc4random() % 10; [NSThread sleepForTimeInterval:sleepInterval];
dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"request: %@ done!", command); block(nil); }); }); }
- (void)testUsingSemphore { dispatch_semaphore_t sem = dispatch_semaphore_create(0);
NSArray *commandArray = @[@"requestcommand1", @"requestcommand2", @"requestcommand3", @"requestcommand4", @"requestcommand5"]; __block NSInteger httpFinishedCount = 0; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [commandArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { [self httpRequest:nil param:@{@"commandKey": obj} completion:^(id response) { NSLock *lock = [[NSLock alloc] init]; [lock lock]; if (++httpFinishedCount == [commandArray count]) { dispatch_semaphore_signal(sem); } [lock unlock]; }]; }];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); NSLog(@"所有任务都已经完成了!"); });
}
|
近期评论