通过GCD把异步方法改成同步

//信号量
- (void)testSema {
    NSLog(@"test sema begin");
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [self testAsync:^(NSString *result) {
        NSLog(@"test sema result:%@",result);
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    NSLog(@"test sema end");
}

//队列组
- (void)testGroup {
    NSLog(@"test group begin");
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self testAsync:^(NSString *result) {
        NSLog(@"test group result:%@",result);
        dispatch_group_leave(group);
    }];
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    NSLog(@"test group end");
}

- (void)testAsync:(void (^)(NSString *result))callback {
    dispatch_async(dispatch_queue_create("testqueue", NULL), ^{
        sleep(2.0);
        callback(@"test_only");
    });
}
2020-02-28 17:47:20 Demo: test sema begin
2020-02-28 17:47:22 Demo: test sema result:test_only
2020-02-28 17:47:22 Demo: test sema end
2020-02-28 17:47:22 Demo: test group begin
2020-02-28 17:47:24 Demo: test group result:test_only
2020-02-28 17:47:24 Demo: test group end

你可能感兴趣的:(通过GCD把异步方法改成同步)