GCD - Dispatch Semaphore
?
先看代码
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); NSMutableArray *array = [[NSMutableArray alloc]init]; dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);//信号量为1 for (int i = 0; i != 10000; ++i) { dispatch_async(queue, ^{ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//等待返回值为1或者大于1,获得执行权利后信号量-1 [array addObject:[NSNumber numberWithInt:i]]; dispatch_semaphore_signal(semaphore);//信号量+1 }); }
?百分之百不崩溃,semaphore的值表示由多少线程可以操作,根据我们的设置,永远只有一个线程可以操作数组。