码迷,mamicode.com
首页 > 其他好文 > 详细

互斥锁、自旋锁、dispatch_once性能对比

时间:2015-08-16 18:10:39      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

代码:

#import <Foundation/Foundation.h>
#import <pthread.h>

extern uint64_t dispatch_benchmark(size_t count, void (^block)(void));

// pthread_mutex_lock
void dispatch_once_pthread(dispatch_once_t *, dispatch_block_t);

// spinlock
void dispatch_once_spinlock(dispatch_once_t *, dispatch_block_t);

int main(int argc, const char * argv[]) {
    
    size_t count = 1000000;
    
    // pthread_mutex_lock
    uint64_t time1 = dispatch_benchmark(count, ^{
        static dispatch_once_t onceToken;
        dispatch_once_pthread(&onceToken, ^{ });
    });
    NSLog(@"dispatch_once_pthread = %llu ns", time1);
    
    // spinlock
    uint64_t time2 = dispatch_benchmark(count, ^{
        static dispatch_once_t onceToken;
        dispatch_once_spinlock(&onceToken, ^{ });
    });
    NSLog(@"dispatch_once_spinlock = %llu ns", time2);
    
    // dispatch_once
    uint64_t time3 = dispatch_benchmark(count, ^{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ });
    });
    NSLog(@"dispatch_once = %llu ns", time3);
    
    return 0;
}

// pthread_mutex_lock
void dispatch_once_pthread(dispatch_once_t *predicate, dispatch_block_t block) {
    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_lock(&mutex);
    if(!*predicate) {
        block();
        *predicate = 1;
    }
    pthread_mutex_unlock(&mutex);
}

// spinlock
void dispatch_once_spinlock(dispatch_once_t *predicate, dispatch_block_t block) {
    static OSSpinLock lock = OS_SPINLOCK_INIT;
    OSSpinLockLock(&lock);
    if(!*predicate) {
        block();
        *predicate = 1;
    }
    OSSpinLockUnlock(&lock);
}

输出:

dispatch_once_pthread = 57 ns
dispatch_once_spinlock = 22 ns
dispatch_once = 15 ns

 

互斥锁、自旋锁、dispatch_once性能对比

标签:

原文地址:http://www.cnblogs.com/loftyspirit/p/4734575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!