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 38 39 40 41 42 43 44
| dispatch_semaphore_t signal;
signal = dispatch_semaphore_create(0);
__block long x = 0;
NSLog(@"0 --> x:%ld",x);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"sleep 1"); sleep(1); NSLog(@"sleep 1 finish, begin signal 1"); x = dispatch_semaphore_signal(signal); NSLog(@"signal 1 --> x:%ld",x); NSLog(@"sleep 2"); sleep(2); NSLog(@"sleep 2 finish, begin signal 2"); x = dispatch_semaphore_signal(signal); NSLog(@"signal 2 --> x:%ld",x);
NSLog(@"sleep 3"); sleep(3); NSLog(@"sleep 3 finish, begin signal 3"); x = dispatch_semaphore_signal(signal); NSLog(@"signal 3 --> x:%ld",x); });
NSLog(@"wait 1 begin"); x = dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER); NSLog(@"wait 1 finish"); NSLog(@"wait 1 --> x:%ld",x); NSLog(@"wait 2 begin"); x = dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER); NSLog(@"wait 2 finish"); NSLog(@"wait 2 --> x:%ld",x); NSLog(@"wait 3 begin"); x = dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER); NSLog(@"wait 3 finish"); NSLog(@"wait 3 --> x:%ld",x);
|