1. //创建全局队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
NSMutableArray *array = [NSMutableArray array];
for(int i = 0 ;i < 1000000;i ++){
dispatch_async(queue, ^{
//dispatch_semaphore 信号量基于计数器的一种多线程同步机制。在多个线程访问共有资源时候,会因为多线程的特性而引发数据 出错的问题,这里使其等待前一个线程访问完array
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[array addObject:[NSNumber numberWithInt:i]];
});
}
2.
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
NSMutableArray *array = [NSMutableArray array];
for(int i = 0 ;i < 1000000;i ++){
dispatch_async(queue, ^{
//给array对象加把锁。防止线程同时访问。
@synchronized (array) {
[array addObject:[NSNumber numberWithInt:i]];
NSLog(@"%d %@",i,array);
}
});
}