多线程:barrier的使用

//
//  ViewController.m
//  12-barrier使用
//
//  Created by gzxzmac on 16/1/29.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () {
    dispatch_queue_t _queue;
}
@property (nonatomic, strong) NSMutableArray *photoList; // 保存下载好的图片
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self download];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"下载了 %zd 张图片",self.photoList.count);
}

// 最快速创建一个可变的数组  @[].mutableCopy
- (NSMutableArray *)photoList {
    if (_photoList == nil) {
        _photoList = [NSMutableArray array];
    }
    return _photoList;
}

- (void)download {

    // NSArray,字典,NSData,..... 线程安全
    // 所有的可变的对象(字典,数组,data) 非线程安全
    /*
     NSArchiver
     NSAutoreleasePool
     NSBundle
     NSCalendar
     NSCoder
     NSCountedSet
     NSDateFormatter
     NSEnumerator
     NSFileHandle
     NSFormatter
     NSHashTable functions
     NSInvocation
     NSJavaSetup functions
     NSMapTable functions
     NSMutableArray
     NSMutableAttributedString
     NSMutableCharacterSet
     NSMutableData
     NSMutableDictionary
     NSMutableSet
     NSMutableString
     NSNotificationQueue
     NSNumberFormatter
     NSPipe
     NSPort
     NSProcessInfo
     NSRunLoop
     NSScanner
     NSSerializer
     NSTask
     NSUnarchiver
     NSUndoManager
     */
    // 一定要使用自定义的并发队列
    _queue = dispatch_queue_create("itcast", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 1000; ++i) {
        dispatch_async(_queue, ^{
            NSLog(@"下载图片%d",i);
            [NSThread sleepForTimeInterval:0.5];
            // 模拟下载
            NSString *imageName = [NSString stringWithFormat:@"%d.jpg",i % 9];
            NSString *path = [[NSBundle mainBundle]pathForResource:imageName ofType:nil];

            UIImage *image = [UIImage imageWithContentsOfFile:path];

            // 使用barrier 之后,全部下载完之后,再统一保存
            // 减少多条线程抢夺资源的问题
            // 在工作中基本不怎么使用(知道)
            dispatch_barrier_async(_queue, ^{
                if (image == nil) {
                    NSLog(@"%d -- %@",i,path);
                }
                NSLog(@"保存图片%@",[NSThread currentThread]);
                // 避免多个线程抢同一块资源
                [self.photoList addObject:image];
            });
        });
    }
}

@end
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值