Tag Archives: 多线程

GCD同步任务实现加锁效果

1、DISPATCH_QUEUE_SERIAL
1.1、串行队列使队列中的任务同步执行,单次只能执行一个任务
1.2、示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#import "ViewController.h"
#import <pthread.h>
@implementation ViewController
static NSUInteger ticketCount_ = 20;
- (void)viewDidLoad
{
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_queue_create("com.yusian.custom-queue", DISPATCH_QUEUE_SERIAL);
    for (int i = 0; i < 5; i++) {
        dispatch_async(queue, ^{
            [self saleTicket];
        });
    }
}
- (void)saleTicket
{
    NSUInteger remain = ticketCount_;
    sleep(1);
    ticketCount_ = --remain;
    NSLog(@"%ld, %@", ticketCount_, [NSThread currentThread]);
}
@end

执行结果:[……]

继续阅读

基于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、锁定状态下,其他线程访[……]

继续阅读