iOS加锁

作者: 喜欢就可以 | 来源:发表于2016-03-21 11:49 被阅读74次
#import <objc/runtime.h>  
#import <objc/message.h>  
#import <libkern/OSAtomic.h>  
#import <pthread.h>  
   
#define ITERATIONS (1024*1024*32)  
- (void)testLock  
{  
    double then, now;  
    unsigned int i, count;  
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  
    OSSpinLock spinlock = OS_SPINLOCK_INIT;  
      
    @autoreleasepool {  
        NSLock *lock = [NSLock new];  
        then = CFAbsoluteTimeGetCurrent();  
        for(i=0;i<ITERATIONS;++i)  
        {  
            [lock lock];  
            [lock unlock];  
        }  
        now = CFAbsoluteTimeGetCurrent();  
        printf("NSLock: %f sec\n", now-then);  
          
   
        then = CFAbsoluteTimeGetCurrent();  
        for(i=0;i<ITERATIONS;++i)  
        {  
            pthread_mutex_lock(&mutex);  
            pthread_mutex_unlock(&mutex);  
        }  
        now = CFAbsoluteTimeGetCurrent();  
        printf("pthread_mutex: %f sec\n", now-then);  
          
          
        then = CFAbsoluteTimeGetCurrent();  
        for(i=0;i<ITERATIONS;++i)  
        {  
            OSSpinLockLock(&spinlock);  
            OSSpinLockUnlock(&spinlock);  
        }  
        now = CFAbsoluteTimeGetCurrent();  
        printf("OSSpinlock: %f sec\n", now-then);  
          
        id obj = [NSObject new];  
          
        then = CFAbsoluteTimeGetCurrent();  
        for(i=0;i<ITERATIONS;++i)  
        {  
            @synchronized(obj)  
            {  
            }  
        }  
        now = CFAbsoluteTimeGetCurrent();  
        printf("@synchronized: %f sec\n", now-then);  
    }  
      
      
}  

相关文章

  • iOS加锁

  • iOS 加锁探究

    1. iOS中的互斥锁 在编程中,引入对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为“互...

  • iOS 加锁方式

    iOS多线程编程中,经常碰到多个线程访问共同的一个资源,在线程相互交互的情况下,需要一些同步措施,来保证线程之间交...

  • 线程锁

    iOS 多线程加锁有很多方式:@synchronized、 NSLock、NSRecursiveLock、NSCo...

  • iOS开发中常用的锁

    iOS开发中常用的锁有如下几种 来比较一下遇到加锁的情况: 1. @synchronized 关键字加锁 2. N...

  • iOS 开发中加锁

    [1].OSSpinLock 自旋锁 [1]自旋锁与互斥锁有点类似,只是自旋锁不会引起调用者睡眠,如果自旋锁已经被...

  • iOS 手势密码加锁

    没有什么废话,直接上代码,需要的直接用。可以参考上一篇文章画图 在View界面

  • iOS 多线程:NSOperation、NSOperationQ

    线程安全解决方案:可以给线程加锁,在一个线程执行该操作的时候,不允许其他线程进行操作。iOS 实现线程加锁有很多种...

  • iOS签名iPhone手机版(支持iOS14,多包同步,一键加锁

    开源Mac和iOS签名加锁客户端,下载地址:https://github.com/even-cheng/ECSig...

  • iOS GCD(六)线程加锁

    iOS GCD (一) 任务+队列 基础组合iOS GCD (二 ) dispatch_group 队列组iO...

网友评论

      本文标题:iOS加锁

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