同步锁:@synchronized()

同步锁:@synchronized()

官方解释:The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time. In this case, however, you do not have to create the mutex or lock object directly.

大概解释一下:使用 @synchronized 可以快速创建互斥锁,你可以不用创建任何互斥锁或是锁定某一对象就可以轻松阻止不同的线程在同一时间去获取相同的锁。

1.@synchronized() 使用场景

在 APP 中,多线程竞争同一资源的时候,会出现一些意想不到的结果,比如数据错乱和安全的问题。

举个🌰

241256038464378.png

问题就是:多个线程去修改票数,导致数据错乱的结果。

那么如何去解决这个问题呢?

同步锁解决资源共享就派上用场了,也就是给共享的资源加锁,让线程一个个地通过,以确保每次线程读取的数据是正确的。

#import "ViewController.h"

@interface ViewController ()

//剩余票数
@property(nonatomic,assign) int leftTicketsCount;
@property(nonatomic,strong)NSThread *thread1;
@property(nonatomic,strong)NSThread *thread2;
@property(nonatomic,strong)NSThread *thread3;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //默认有20张票
    self.leftTicketsCount=10;
    //开启多个线程,模拟售票员售票
    
    self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
    
    self.thread1.name=@"售票员A";
    
    self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
    
    self.thread2.name=@"售票员B";

    self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
    
    self.thread3.name=@"售票员C";
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //开启线程
    [self.thread1 start];
    [self.thread2 start];
    [self.thread3 start];
}

-(void)sellTickets
{
    while (1) {
        
        @synchronized(self){//只能加一把锁
            //1.先检查票数
            int count=self.leftTicketsCount;
            if (count>0) {
                //暂停一段时间
                [NSThread sleepForTimeInterval:0.002];
                //2.票数-1
                
                self.leftTicketsCount= count-1;
                //获取当前线程
                NSThread *current=[NSThread currentThread];
                NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
            }
            else{
                //退出线程
                NSLog(@"over!!!");
                NSLog(@"%@",[[NSThread currentThread] name]);
                [NSThread exit];//
                
            }
        }
        NSLog(@"name:%@ 解锁成功!",[[NSThread currentThread] name]);
    }
}
@end

打印结果:

QQ20161021-0.png

使用 @synchronized() 可以很轻松就解决线程同步存在的隐患,但是在性能上却不太友好,需要消耗大量的CPU资源, 主要是通过牺牲性能换来语法上的简洁与可读。为什么这样说呢?我们来看看官方文档的解释:

As a precautionary measure, the @synchronized block implicitly adds an exception handler to the protected code. This handler automatically releases the mutex in the event that an exception is thrown. This means that in order to use the @synchronized directive, you must also enable Objective-C exception handling in your code. If you do not want the additional overhead caused by the implicit exception handler, you should consider using the lock classes.

大概解释就是:在@synchronized 块中,隐藏地添加了一段异常处理的代码,当异常抛出时,互斥锁自动解开。如果不想使用这一段异常处理代码,那就需要使用其他锁来解决线程同步的问题吧。

如果想知道@synchronized 是如何实现的,请移步于原理实现

延伸:下面简单减少一下 iOS 中常见一些锁的概念

mutex

A mutually exclusive (or mutex) lock acts as a protective barrier around a resource. A mutex is a type of semaphore that grants access to only one thread at a time. If a mutex is in use and another thread tries to acquire it, that thread blocks until the mutex is released by its original holder. If multiple threads compete for the same mutex, only one at a time is allowed access to it.

互斥锁在资源的周围树立了屏障。 互斥是一种类型的信号量,它一次只允许访问一个线程。 如果一个互斥体在使用,另一个线程试图获取它,该线程阻塞,直到互斥体被其原始持有者释放。 如果多个线程竞争同一互斥体,则一次只允许一个线程访问它。

Recursive lock

A recursive lock is a variant on the mutex lock. A recursive lock allows a single thread to acquire the lock multiple times before releasing it. Other threads remain blocked until the owner of the lock releases the lock the same number of times it acquired it. Recursive locks are used during recursive iterations primarily but may also be used in cases where multiple methods each need to acquire the lock separately.

递归锁是互斥锁上的一个变体。 递归锁允许单个线程在释放锁之前多次获取锁。 其他线程保持阻塞,直到锁的所有者释放锁的次数与它获得的次数相同。 递归锁在递归迭代期间主要使用,但也可以在多个方法每个需要单独获取锁的情况下使用。

Read-write lock

A read-write lock is also referred to as a shared-exclusive lock. This type of lock is typically used in larger-scale operations and can significantly improve performance if the protected data structure is read frequently and modified only occasionally. During normal operation, multiple readers can access the data structure simultaneously. When a thread wants to write to the structure, though, it blocks until all readers release the lock, at which point it acquires the lock and can update the structure. While a writing thread is waiting for the lock, new reader threads block until the writing thread is finished. The system supports read-write locks using POSIX threads only. For more information on how to use these locks, see the pthread man page.

读写锁也称为共享排它锁。 这种类型的锁通常用于大规模操作,并且如果受保护的数据结构被频繁地读取并且仅仅偶尔被修改,则可以显着地提高性能。 在正常操作期间,多个读取器可以同时访问数据结构。 当线程想要写入结构时,它阻塞,直到所有读者释放锁,此时它获取锁并且可以更新结构。 当写线程正在等待锁时,新的读线程阻塞直到写线程完成。 系统仅支持POSIX线程使用读写锁。 有关如何使用这些锁的更多信息,请参见pthread手册页。

Distributed lock

A distributed lock provides mutually exclusive access at the process level. Unlike a true mutex, a distributed lock does not block a process or prevent it from running. It simply reports when the lock is busy and lets the process decide how to proceed.

分布式锁在过程中提供了互斥访问。 与真正的互斥体不同,分布式锁不会阻止进程或阻止进程运行。 它只是报告锁定是否忙,并让进程决定如何继续。

Spin lock

A spin lock polls its lock condition repeatedly until that condition becomes true. Spin locks are most often used on multiprocessor systems where the expected wait time for a lock is small. In these situations, it is often more efficient to poll than to block the thread, which involves a context switch and the updating of thread data structures. The system does not provide any implementations of spin locks because of their polling nature, but you can easily implement them in specific situations. For information on implementing spin locks in the kernel, see Kernel Programming Guide.

自旋锁重复轮询其锁定条件,直到该条件变为真。 自旋锁最常用于多处理器系统上,其中锁的预期等待时间很小。 在这些情况下,轮询通常比阻塞线程更有效,这涉及上下文切换和线程数据结构的更新。 由于其轮询性质,系统不提供任何自旋锁的实现,但是您可以在特定情况下轻松实现它们。 有关在内核中实现自旋锁的信息,请参阅内核编程指南。

Double-checked lock

A double-checked lock is an attempt to reduce the overhead of taking a lock by testing the locking criteria prior to taking the lock. Because double-checked locks are potentially unsafe, the system does not provide explicit support for them and their use is discouraged.

双重检查锁是试图通过在获取锁定之前测试锁定标准来减少获取锁定的开销。 由于双重检查锁可能不安全,因此系统不会为它们提供显式支持,并且不建议使用它们。

参考博客:

线程安全

官方文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容