-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteLockTest.m
More file actions
61 lines (48 loc) · 1.05 KB
/
ReadWriteLockTest.m
File metadata and controls
61 lines (48 loc) · 1.05 KB
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
//
// ReadWriteLockTest.m
// WGFcodeNotes
//
// Created by 白菜 on 2022/10/10.
// Copyright © 2022 WG. All rights reserved.
//
#import "ReadWriteLockTest.h"
#import <pthread.h>
@interface ReadWriteLockTest()
@property(nonatomic, assign) pthread_rwlock_t lock;
@end
@implementation ReadWriteLockTest
-(instancetype)init {
self = [super init];
if (self) {
//初始化读写锁
pthread_rwlock_init(&_lock, NULL);
}
return self;
}
-(void)otherTest {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for (int i = 0 ; i < 10; i++) {
dispatch_async(queue, ^{
[self __read];
});
dispatch_async(queue, ^{
[self __write];
});
}
}
-(void)__read{
//读 - 加锁
pthread_rwlock_rdlock(&_lock);
sleep(1.0);
NSLog(@"%s",__func__);
//读 - 解锁
pthread_rwlock_unlock(&_lock);
}
-(void)__write {
//写 - 加锁
pthread_rwlock_wrlock(&_lock);
NSLog(@"%s",__func__);
//写 - 解锁
pthread_rwlock_unlock(&_lock);
}
@end