Repository navigation
Expand file tree
/
Copy pathViewController.m
More file actions
109 lines (87 loc) · 2.82 KB
/
Copy pathViewController.m
File metadata and controls
109 lines (87 loc) · 2.82 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//
// ViewController.m
// InterviewExampleCode
//
// Created by DragonLi on 2018/1/15.
// Copyright © 2018年 XiTu Inc. All rights reserved.
//
#import "ViewController.h"
#import "LFLConstInlineHeader.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// LFLImagePlaceholder()
// [self dispatch_queue_tDemo];
// [self dispatch_semaphore_tDemo];
}
/**
多个图片上传后, block 回调 URL ,按照顺序装入新数组
*/
- (void)picsUploadDemoimages:(NSArray *)images{
NSMutableArray *picUrlArray = [NSMutableArray array];
for (int i = 0; i < images.count; i++) {
[picUrlArray addObject:[NSNull null]];
}
dispatch_queue_t queue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t dispatchGroup = dispatch_group_create();
for (NSInteger i = 0; i < images.count; i ++) {
// UIImage *image = images[i];
dispatch_group_async(dispatchGroup, queue, ^{
dispatch_group_enter(dispatchGroup);
[self uploadDemoSucessBlock:^(NSString *url) {
NSLock * lock = [[NSLock alloc]init];
[lock lock];
picUrlArray[i] = url;
[lock unlock];
dispatch_group_leave(dispatchGroup);
} ErrorBlock:^{
dispatch_group_leave(dispatchGroup);
} index:i];
});
}
dispatch_group_notify(dispatchGroup, queue, ^{
if (picUrlArray.count == images.count && picUrlArray.firstObject != nil) {
// 已经传完毕
}
});
}
- (void)uploadDemoSucessBlock:(void (^)(NSString *))SucessBlock
ErrorBlock:(void (^)(void))errorBlock
index:(NSInteger)index{
if (SucessBlock) {
SucessBlock([NSString stringWithFormat:@"%ld-PicURL",index]);
}
}
/**
保持线程同步
*/
- (void)dispatch_queue_tDemo{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block int j = 0;
dispatch_async(queue, ^{ //
j = 100;
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"%zd", j);
}
/**
为线程加锁
*/
- (void)dispatch_semaphore_tDemo{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
for (int i = 0; i < 100; i++) {
dispatch_async(queue, ^{
// 加锁
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"i = %zd %@", i, semaphore);
// 解锁
dispatch_semaphore_signal(semaphore);
});
}
}
@end