美文网首页
atomic 和 nonatomic

atomic 和 nonatomic

作者: FishSha | 来源:发表于2017-09-10 13:40 被阅读15次

    解释就没必要的,网上、书上太多说明了,主要说说他们的区别,和一些容易理解错误的地方。

    atomic并不是线程安全:

    在网上查询资料,大部分都会说,申明了atomic就是线程安全,nonatomic就不是线程安全,屁!

    atomic严格意义上说,只是一定程度上减少了多线程读写错误的概率,真正实现读写安全的方法,其实是在对应属性的set/get方法里包一层@synchroized(self){// do some thing},一个小的demo如下:

    h文件申明id属性 m文件设置set/get属性

    这里在set/get中包了一层synchronized(self){// do some thing}

    这里循环创建多个线程访问id属性

    这里为了方便,打印了线程的名称和对应id的值

    输出结果

    可以看到,都是id的set方法执行完成后的9999.

    下面将@synchroized(self){ //do some thing}去掉看下

    先注视掉

    看结果

    一部分都错了

    原因看文档有说:

    Using the @synchronized Directive

    The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time. In this case, however, you do not have to create the mutex or lock object directly. Instead, you simply use any Objective-C object as a lock token, as shown in the following example:

    - (void)myMethod:(id)anObj

    {

    @synchronized(anObj)

    {

    // Everything between the braces is protected by the @synchronized directive.

    }

    }

    The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block. If you execute the preceding method in two different threads, passing a different object for the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. If you pass the same object in both cases, however, one of the threads would acquire the lock first and the other would block until the first thread completed the critical section.

    As a precautionary measure, the @synchronized block implicitly adds an exception handler to the protected code. This handler automatically releases the mutex in the event that an exception is thrown. This means that in order to use the @synchronized directive, you must also enable Objective-C exception handling in your code. If you do not want the additional overhead caused by the implicit exception handler, you should consider using the lock classes.

    For more information about the @synchronized directive, see The Objective-C Programming Language.

    参考:https://www.douban.com/note/486901956/

    相关文章

      网友评论

          本文标题:atomic 和 nonatomic

          本文链接:https://www.haomeiwen.com/subject/pigzjxtx.html