美文网首页
iOS中锁的研究

iOS中锁的研究

作者: 张xd | 来源:发表于2015-12-09 14:52 被阅读104次

    #define ITERATIONS (1024*1024*32)

    int main(int argc, const char * argv[]) {

    double then,now;

    unsigned int i;

    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();

    NSLog(@"NSLock time is      %f sec",now - then);

    then = CFAbsoluteTimeGetCurrent();

    for (i = 0; i < ITERATIONS; i ++) {

    pthread_mutex_lock(&mutex);

    pthread_mutex_unlock(&mutex);

    }

    now = CFAbsoluteTimeGetCurrent();

    NSLog(@"pthread_mutex time is %f sec",now - then);

    then = CFAbsoluteTimeGetCurrent();

    for (i = 0; i < ITERATIONS; i ++) {

    OSSpinLockLock(&spinLock);

    OSSpinLockUnlock(&spinLock);

    }

    now = CFAbsoluteTimeGetCurrent();

    NSLog(@"OSSpinLock time is    %f sec",now - then);

    id obj = [NSObject new];

    then = CFAbsoluteTimeGetCurrent();

    for (i = 0; i < ITERATIONS; i ++) {

    @synchronized(obj)

    {

    }

    }

    now = CFAbsoluteTimeGetCurrent();

    NSLog(@"@synchronized time is  %f sec",now - then);

    }

    return 0;

    }

    得到的结果如下:

    相关文章

      网友评论

          本文标题:iOS中锁的研究

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