GCD信号量[简记]

简单记录一下GCD信号量的使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
ViewController * vc = [ViewController new];
vc.myBlock = ^{
dispatch_semaphore_signal(semaphore);
NSLog(@"信号量 +1");
};

//延迟2秒执行myBlock
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),dispatch_get_global_queue(0, 0), ^{
vc.myBlock();
NSLog(@"等待2秒结束");
});

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"接收成功");

执行结果:

1
2
3
2017-08-20 15:45:30.747164+0800 OC[48972:1332777] 等待2秒结束
2017-08-20 15:45:30.747477+0800 OC[48972:1332777] 信号量 +1
2017-08-20 15:45:30.747493+0800 OC[48972:1332730] 接收成功