zoukankan      html  css  js  c++  java
  • 关于@synchronized(self)的用法

    @synchronized 的作用是创建一个互斥锁,保证此时没有其它线程对self对象进行修改。这个是objective-c的一个锁定令牌,防止self对象在同一时间内被其它线程访问,起到线程的保护作用。 一般在公用变量的时候使用,如单例模式或者操作类的static变量中使用。

    # import "NetworkManager.h"

    staticNetworkManager*network =nil;

    @implementationNetworkManager

    +(NetworkManager*)getNetworkInstance{

    @synchronized(self){

    if(nil== network){

    network =[[NetworkManager alloc] init];

    {

    }

    return network;

    }

    英文文档:

    Using the @synchronizedDirective(指令)
    The@synchronized directive is a convenient way to create mutex locks(互斥锁) on the fly inObjective-C code.The@synchronized directive does what any other mutex lock would doit prevents(预防) different threads from acquiring the same lock at the same time.Inthiscase, however, you donot have to create the mutex orlockobject directly.Instead, you simply use any Objective-C objectas a lock token with@synchronized

     

    Theobject 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 objectfor the anObj parameter on each thread, each would take its lockandcontinue processing without being blocked by the other.If you pass the same objectin 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 donot 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 TheObjective-C ProgrammingLanguage.
  • 相关阅读:
    总结类初始化时的代码执行顺序
    Calcite数据源适配器对时间字段的操作问题
    如何自定义一个Calcite对Tablesaw查询的适配器
    Redis集群 Redis Cluster
    培养代码逻辑
    在线查看office文件的两种方法
    WPF Prism框架合集(9.Dialog)
    WPF Prism框架合集(8.Navigation)
    WPF Prism框架合集(7.Mvvm)
    springboot @OneToOne 解决JPA双向死循环/返回json数据死循环
  • 原文地址:https://www.cnblogs.com/lzjsky/p/2995678.html
Copyright © 2011-2022 走看看