-
Notifications
You must be signed in to change notification settings - Fork 0
/
Contents.swift
133 lines (113 loc) · 2.41 KB
/
Contents.swift
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import Foundation
let longTask = {
print("Starting long task")
sleep(2)
print("Finished long task")
}
let longRandom: () -> Int = {
sleep(1)
return Int.random(in: 0 ... 10)
}
let queue = DispatchQueue(label: "Serial queue")
let group = DispatchGroup()
queue.async(group: group) {
sleep(1)
print("Task 1 done")
}
queue.async(group: group) {
sleep(2)
print("Task 2 done")
}
group.wait()
print("All tasks done")
// MARK: - Sync vs. Async
//print("Starting async")
//DispatchQueue.global().sync {
// longTask()
// print("Hello, I am on async")
//}
//
//print("Code after async")
//
//print("Starting sync")
//DispatchQueue.global().sync {
// longTask()
// print("Hello, I am on sync")
//}
//
//print("Code after sync")
// MARK: - Dispatch groups
let group = DispatchGroup()
//DispatchQueue.global().async(group: group) {
// longTask()
//}
//
//group.notify(queue: .global()) {
// print("Finished group")
//}
//for _ in 0 ..< 5 {
// group.enter()
//
// DispatchQueue.global().async {
// longTask()
// group.leave()
// }
//}
//
//group.notify(queue: .global()) {
// print("Finished 5 tasks")
//}
//
//print("The code after the loop")
// MARK: - Serial vs. Concurrent queues
//let serialQueue = DispatchQueue(label: "com.heartsker.serial-queue")
//let concurrentQueue = DispatchQueue(label: "com.heartsker.concurrent-queue", attributes: .concurrent)
//
//let serialGroup = DispatchGroup()
//let concurrentGroup = DispatchGroup()
//
//let start1 = Double(DispatchTime.now().uptimeNanoseconds)
//
//serialGroup.enter()
//
//serialQueue.sync {
// longTask()
// longTask()
// longTask()
// serialGroup.leave()
//}
//
//serialGroup.notify(queue: serialQueue) {
// print("Done serial")
//}
//
//let end1 = Double(DispatchTime.now().uptimeNanoseconds)
//
//let start2 = Double(DispatchTime.now().uptimeNanoseconds)
//
//concurrentGroup.enter()
//
//concurrentQueue.sync {
// longTask()
// longTask()
// longTask()
// concurrentGroup.leave()
//}
//
//concurrentGroup.notify(queue: concurrentQueue) {
// print("Done concurrent")
//}
//
//let end2 = Double(DispatchTime.now().uptimeNanoseconds)
//
//print("Serial time: \((end1 - start1) / 1_000_000) ms")
//print("Concurrent time: \((end2 - start2) / 1_000_000) ms")
//DispatchQueue.global().sync {
// print("Hello")
//}
//
//DispatchQueue.global().async {
// print("Bye")
//}
//
//print("All")