2018-04-24

NSUserDefault是否线程安全?
答:安全
验证过程:

 NSMutableArray *array = [[NSMutableArray alloc] init];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_apply(10, queue, ^(size_t i) {
        NSLog(@"begin block:%zd",i);
        sleep(1);
//         [array addObject:@(i)];
        [[NSUserDefaults standardUserDefaults]setInteger:i forKey:@"isThreadSafe"];
        NSLog(@"end block:%zd",i);
    });

正常运行,运行结果如下:

2018-07-24 10:44:18.523054+0800 Test1[80485:18532648] begin block:0
2018-07-24 10:44:18.523085+0800 Test1[80485:18532701] begin block:2
2018-07-24 10:44:18.523054+0800 Test1[80485:18532699] begin block:1
2018-07-24 10:44:18.523104+0800 Test1[80485:18532698] begin block:3
2018-07-24 10:44:19.523846+0800 Test1[80485:18532648] end block:0
2018-07-24 10:44:19.523997+0800 Test1[80485:18532648] begin block:4
2018-07-24 10:44:19.526144+0800 Test1[80485:18532701] end block:2
2018-07-24 10:44:19.526294+0800 Test1[80485:18532701] begin block:5
2018-07-24 10:44:19.526322+0800 Test1[80485:18532699] end block:1
2018-07-24 10:44:19.526421+0800 Test1[80485:18532698] end block:3
2018-07-24 10:44:19.526474+0800 Test1[80485:18532699] begin block:6
2018-07-24 10:44:19.526772+0800 Test1[80485:18532698] begin block:7
2018-07-24 10:44:20.525035+0800 Test1[80485:18532648] end block:4
2018-07-24 10:44:20.525195+0800 Test1[80485:18532648] begin block:8
2018-07-24 10:44:20.531290+0800 Test1[80485:18532701] end block:5
2018-07-24 10:44:20.531461+0800 Test1[80485:18532699] end block:6
2018-07-24 10:44:20.531616+0800 Test1[80485:18532698] end block:7
2018-07-24 10:44:20.531724+0800 Test1[80485:18532701] begin block:9
2018-07-24 10:44:21.526263+0800 Test1[80485:18532648] end block:8
2018-07-24 10:44:21.534327+0800 Test1[80485:18532701] end block:9

采用非线程安全的数组

NSMutableArray *array = [[NSMutableArray alloc] init];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_apply(10, queue, ^(size_t i) {
        NSLog(@"begin block:%zd",i);
        sleep(1);
        [array addObject:@(i)];
        //        [[NSUserDefaults standardUserDefaults]setInteger:i forKey:@"isThreadSafe"];
        NSLog(@"end block:%zd",i);
    });

运行结果:


image.png

你可能感兴趣的:(2018-04-24)