Tag Archives: pthread_mutex

基于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

输出结果:[……]

继续阅读