@synchronized vs NSLock vs pthread_mutex_lock

@synchronized 编译器指令

@synchronized(self) {
//do something
}

以上代码会被编译器转换成

pthread_mutex_t self_mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
  pthread_mutex_lock(&self_mutex);
  //do something
  pthread_mutex_unlock(&self_mutex);

pthread_mutex_lock

从以上代码观察, pthread_mutex_lock 和 @synchronized 在转换之后,本质上是一样的。但是代码的执行效率会略有不同,@synchronized 指令会根据情况自动选择合适的 pthread 锁类型,像递归锁,互斥锁等。

NSLock

NSLock *lock = [[NSLock alloc] init];
[lock tryLock];
//do something
[lock unlock];

参考:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW3

http://stackoverflow.com/questions/1215330/how-does-synchronized-lock-unlock-in-objective-c/1215541#1215541

http://googlemac.blogspot.com/2006/10/synchronized-swimming.html

http://blog.sina.com.cn/s/blog_62274fd70100gf0k.html

http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_init.html

https://www.ibm.com/developerworks/cn/linux/thread/posix_thread1/

https://www.ibm.com/developerworks/cn/linux/thread/posix_thread2/

https://www.ibm.com/developerworks/cn/linux/thread/posix_thread3/