Tag Archives: 线程锁

基于pthread_mutex封装的锁NSLock、NSCondition、NSConditionLock、NSRecursiveLock、@Synchronized

参考链接:iOS多线程中的几种加锁类型OSSpinLock、os_unfair_lock、pthread_mutex

1、pthread_mutex是c语言实现的跨平台互斥锁,应该是一种主流锁吧,OC多种形态的锁都是基于pthread_mutex,常见的有NSLock、NSCondition、NSConditionLock、NSRecursiveLock、@Synchronized

2、各种锁的基本使用
2.1、NSLock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#import "ViewController.h"
#import <pthread.h>
 
@interface ViewController ()
{
    NSLock           *_lock;
}
@end
 
@implementation ViewController
static NSUInteger ticketCount = 20;
- (void)viewDidLoad
{
    [super viewDidLoad];
    _lock = [[NSLock alloc] init];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 5; i++) {
            [self saleTickte];
        }
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 5; i++) {
            [self saleTickte];
        }
    });
}
 
- (void)saleTickte
{
    [_lock lock];
    // lockBeforeDate:方法能在指定时间后自动解锁
    // [_lock lockBeforeDate:[NSDate dateWithTimeIntervalSinceNow:3]];
    NSUInteger remain = ticketCount;
    sleep(0.5);
    ticketCount = --remain;
    NSLog(@"%ld-%@", ticketCount, [NSThread currentThread]);
    [_lock unlock];
}
@end

输出结果:[……]

继续阅读

iOS多线程中的几种加锁类型OSSpinLock、os_unfair_lock、pthread_mutex

1、基本介绍
1.1、OSSpinLock
1.1.1、自旋锁,iOS10及以后版本已标记过期;
1.1.2、锁定状态下,其他线程访问时处于忙等状态
1.1.3、存在优先级反转的问题而被放弃;
1.2、os_unfair_lock
1.2.1、互斥锁
1.2.2、锁定状态下,其他线程访[……]

继续阅读