atomic与线程安全

iOS开发中,property用atomic修饰并不是真正的线程安全

创建

@property(atomic, assign)int number;


开启异步线程同时对self.number进行操作

dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [self operationA];

    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        [self operationB];

    });

//操作A

-(void)operationA{

    for(int i = 0; i <10; i ++)

    {

        self.number = self.number+1;

        NSLog(@"operationA: %d\n", self.number);

    }

}

//操作B

-(void)operationB{

    for(int i = 0; i <10; i ++)

    {

        self.number = self.number+1;

        NSLog(@"operationB: %d\n", self.number);

    }

}

执行结果

2018-11-30 09:19:46.606098+0800 Runtime[89190:19183050] operationA: 1

2018-11-30 09:19:46.606098+0800 Runtime[89190:19183052] operationB: 2

2018-11-30 09:19:46.606330+0800 Runtime[89190:19183050] operationA: 3

2018-11-30 09:19:46.606375+0800 Runtime[89190:19183052] operationB: 4

2018-11-30 09:19:46.606415+0800 Runtime[89190:19183050] operationA: 5

2018-11-30 09:19:46.606456+0800 Runtime[89190:19183052] operationB: 6

2018-11-30 09:19:46.606492+0800 Runtime[89190:19183050] operationA: 7

2018-11-30 09:19:46.606539+0800 Runtime[89190:19183052] operationB: 8

2018-11-30 09:19:46.606971+0800 Runtime[89190:19183052] operationB: 9

2018-11-30 09:19:46.607266+0800 Runtime[89190:19183050] operationA: 10

2018-11-30 09:19:46.607485+0800 Runtime[89190:19183052] operationB: 11

2018-11-30 09:19:46.607670+0800 Runtime[89190:19183050] operationA: 12

2018-11-30 09:19:46.607981+0800 Runtime[89190:19183052] operationB: 13

2018-11-30 09:19:46.608171+0800 Runtime[89190:19183050] operationA: 14

2018-11-30 09:19:46.608554+0800 Runtime[89190:19183052] operationB: 15

2018-11-30 09:19:46.608684+0800 Runtime[89190:19183050] operationA: 16

2018-11-30 09:19:46.609233+0800 Runtime[89190:19183052] operationB: 17

2018-11-30 09:19:46.609292+0800 Runtime[89190:19183050] operationA: 18

2018-11-30 09:19:46.610658+0800 Runtime[89190:19183052] operationB: 19

2018-11-30 09:19:46.610914+0800 Runtime[89190:19183050] operationA: 20


self.number打印结果从1到20且没有重复数字表示在执行numbe的setter方法时是线程安全的,但是operationA操作self.number时,operationB也同时能操作表示atomic并不能保证真正的线程安全.

你可能感兴趣的:(atomic与线程安全)