变更记录

序号 录入时间 录入人 备注
1 2017-06-29 Alfred Jiang -

方案名称

并发编程 - 线程安全且高吞吐量的缓存模型

关键字

并发编程 \ 多线程 \ 线程安全 \ 缓存

需求场景

  1. 线程安全且高吞吐量的缓存模型
  2. 将读写锁应用于并发读写

参考链接

  1. 《高性能 iOS 应用开发》

详细内容

实现一个多线程场景下可以并行地读取数据,但是修改数据时通过互斥锁保证安全的缓存模型。

HPCache.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//
// HPCache.h
// HighPerformance
//
// Created by Gaurav Vaish on 12/14/14.
// Copyright (c) 2014 Gaurav Vaish. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface HPCache : NSObject

+(HPCache *)sharedInstance;

-(id)objectForKey:(id<NSCopying>)key;
-(void)setObject:(id)object forKey:(id<NSCopying>)key;
-(id)removeObjectForKey:(id<NSCopying>)key;

-(void)clear;

@end

HPCache.m

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// HPCache.m
// HighPerformance
//
// Created by Gaurav Vaish on 12/14/14.
// Copyright (c) 2014 Gaurav Vaish. All rights reserved.
//

#import "HPCache.h"

static const char* const kCacheQueueName = "com.m10v.hperf.cache.queue";

@interface HPCache ()

@property (nonatomic, readonly) NSMutableDictionary *cacheObjects;
@property (nonatomic, readonly) dispatch_queue_t queue;

@end


@implementation HPCache

-(instancetype)init {
if(self = [super init]) {
_cacheObjects = [NSMutableDictionary dictionary];
_queue = dispatch_queue_create(kCacheQueueName, DISPATCH_QUEUE_CONCURRENT);
}
return self;
}

+(HPCache *)sharedInstance {
static HPCache *instance = nil;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[HPCache alloc] init];
});
return instance;
}


-(void)setObject:(id)object forKey:(id<NSCopying>)key {
dispatch_barrier_async(self.queue, ^{
[self.cacheObjects setObject:object forKey:key];
});
}

-(id)objectForKey:(id<NSCopying>)key {
__block id rv = nil;

dispatch_sync(self.queue, ^{
[NSThread sleepForTimeInterval:0.01];
rv = [self.cacheObjects objectForKey:key];
});

return rv;
}

-(void)clear {
dispatch_sync(self.queue, ^{
[self.cacheObjects removeAllObjects];
});
}

-(id)removeObjectForKey:(id<NSCopying>)key {
__block id rv = nil;

dispatch_sync(self.queue, ^{
rv = [self.cacheObjects objectForKey:key];
[self.cacheObjects removeObjectForKey:key];
});
return rv;
}

@end

效果图

(无)

备注

(无)