search

Home  >  Q&A  >  body text

ios - OC中的方法加锁

高洛峰高洛峰2889 days ago367

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-18 09:24:15

    Method-level control has no language-level modifiers, and code blocks can be locked.

    There are many ways to lock.

    1. @synchronized

    2. NSLock

    3. pthread_mutex

    4. dispatch_semaphore

    5. OSSpinLock

    1. @synchronized

    @interface A : NSObject {
        NSObject _lock;
    }
    
    - (void)func {
        @synchronized(_lock) {
        // do something
        }
    }

    2. NSLock

    - (void) func {
        [_lock lock];
        // do something
        [_lock unlock];
    }

    3. pthread_mutex

    @interface A : NSObject {
        pthread_mutex_t lock;
    }
    
    - (instance)init {
        // 省略
        pthread_mutex_init(&_lock, NULL);
    }
    
    - (void)func {
        pthread_mutex_lock(&lock);
        // do something
        
        pthread_mutex_unlock(&lock);
    }

    4. dispatch_semaphore

    
    @interface A : NSObject {
        dispatch_semaphore_t _semaphore; 
    }
    
    - (instance)init {
        // 省略
        _semaphore = dispatch_semaphore_create(1);
    }
    
    - (void)func {
        dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
        // do something
        
        dispatch_semaphore_signal(_semaphore);
    }

    5.OSSpinLock

    Since spin lock is no longer safe in iOS, it will not be introduced here. For details, you can read this blog
    OSSpinLock is no longer safe

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:24:15

    GCD+block for

    .

    reply
    0
  • Cancelreply