[25] GCD Flashcards

(43 cards)

1
Q

What is a task? GCD

A

In Swift, this is usually a closure (a block of code).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is queue? GCD

A

A queue is an ordered list of tasks.

Tasks are submitted as closures to the queue in a first-in, first-out (FIFO) order

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is GCD? GCD

A

Grand Central Dispatch: a low-level C API to schedule work on queues and utilize multicore concurrency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what is a thread? GCD

A

Is the system-level execution context (in the CPU) where a task runs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Main vs global queues? GCD

A

Main queue = main thread (UI). Global queues = background concurrent (non-UI).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Difference between Queue and Thread in GCD

A

Queue → an ordered list of tasks (FIFO).
Thread → a system resource (execution context on the CPU).
GCD takes tasks from a queue and assigns them to threads as needed.

As a developer, you say “run this on queue Y,” and GCD decides the thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to dispatch work to the main queue? GCD

A
DispatchQueue.main.async { /* UI updates */ }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

sync vs async on a queue? GCD

A

sync blocks caller until finished; async returns to caller immediately.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Serial vs concurrent queue? GCD

A

Serial runs one task at a time (only on thread is assigned)
Concurrent runs multiple threads (as much as the system has resources for) simultaneously.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Create a serial queue GCD

A
let q = DispatchQueue(label: "com.acme.serial")
q.async {
    // runs off the caller thread, tasks execute one-by-one
    let result = heavyWork()
    DispatchQueue.main.async {
        updateUI(with: result)
    }
}
q.sync {
    // blocks the current thread until this finishes
    doSomething()
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Create a concurrent queue GCD

A
let q = DispatchQueue(label: "com.acme.concurrent", attributes: .concurrent)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

QoS purpose GCD

A

Hint to system about priority: .userInteractive, .userInitiated, .utility, .background.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Set QoS on queue GCD

A
let q = DispatchQueue(label: "work", qos: .userInitiated)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Why avoid heavy work on main? GCD

A

Blocks rendering/input → jank or ANRs (app not responding)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a barrier block? GCD

A

If you have shared mutable state (e.g. a variable state), concurrent reads are fine, but concurrent writes (or read+write) can corrupt data.

Exclusive block on concurrent queue; acts like a write lock.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Barrier example GCD

A
let q = DispatchQueue(label: "state", attributes: .concurrent)
q.async(flags: .barrier) { 
state = .ready 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Delay work with GCD GCD

A
DispatchQueue.main.asyncAfter(deadline: .now()+0.3) {
... 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is DispatchGroup? GCD

A

Group async tasks; get notified when all complete.

19
Q

DispatchGroup example GCD

A
let group = DispatchGroup()
for url in urls { 
    group.enter()
    fetch(url) { _ in
        g.leave()
    }
}
g.notify(queue: .main){ 
    done()
}
20
Q

What is wait in a DispatchGroup?

A

A synchronous method that will block the current queue until all the jobs have finished.

let group = DispatchGroup()

someQueue.async(group: group) { ... }
someQueue.async(group: group) { ... }
someOtherQueue.async(group: group) { ... }

if group.wait(timeout: .now() + 60) == .timedOut {
  print("The jobs didn’t finish in 60 seconds")
}

Note: Remember, this blocks the current thread; never ever call wait on the main queue.

21
Q

Code the following: GCD
- serial queue
- async queue
- main queue
- global

A

Serial: (you create)

let serialQ = DispatchQueue(label: "com.example.serial")

Concurrent: (you create)

let concurrentQ = DispatchQueue(label: "com.example.concurrent", attributes: .concurrent)

Main: (system-provided)(not concurrent)

let mainQ = DispatchQueue.main

Global: (system-provided) (concurrent)

let globaQ = DispatchQueue.global(qos: .userInitiated)
22
Q

What is DispatchSemaphore? GCD

A

Counting semaphore to limit concurrency. (If you wish to enable four network downloads at once, then you pass in 4)

OR

bridge callbacks (use sparingly).

23
Q

Semaphore limit example GCD

A
let sem = DispatchSemaphore(value: 3)
for job in jobs {
  DispatchQueue.global().async {
    sem.wait()
    doWork(job)
    sem.signal()
  } 
}
24
Q

Self-deadlock pattern GCD

A

Calling sync on the same serial queue you’re on.

25
Deadlock code smell `GCD`
```swift let q = DispatchQueue(label: "s") q.async { q.sync { print("deadlock") } } ```
26
Why DispatchWorkItem? `GCD`
DispatchWorkItem is a class that provides an actual object to hold the code you wish to submit to a queue. ``` let queue = DispatchQueue(label: "xyz") queue.async { print("The block of code ran!") } ``` Cancellation before start, custom QoS/flags, notify chaining.
27
Work item cancel `GCD`
``` let item = DispatchWorkItem { heavy() } q.async(execute: item) item.cancel() ```
28
Detect current queue? `GCD`
Use queue-specific keys or rely on actor/task context; don’t branch on labels.
29
Thread explosion cause `GCD`
Unbounded concurrency (too many global asyncs).
30
OperationQueue vs GCD `GCD`
OperationQueue = higher-level (deps, cancel); built on GCD.
31
Which should you choose? `GCD` or Operations?
if you’re just working with methods or chunks of code that need to be executed, GCD is a fitting choice. If you’re working with objects that need to encapsulate data and functionality then you’re more likely to utilize Operations.
32
Targeting queues `GCD`
```swift serial.setTarget(queue: DispatchQueue.global(qos: .background)) ```
33
Common DispatchSource? `GCD`
Timers, file descriptors, signals, process.
34
DispatchSourceTimer sample `GCD`
```swift let t = DispatchSource.makeTimerSource(queue: .main) t.schedule(deadline: .now(), repeating: 1) t.setEventHandler { tick() } t.resume() ```
35
Atomic updates via GCD `GCD`
Use a serial queue or concurrent + barrier around shared mutable state.
36
Why not spinlocks? `GCD`
Waste CPU/energy; prefer queues, os_unfair_lock, or actors.
37
Priority inversion handling `GCD`
GCD inherits/boosts QoS; keep critical sections short and QoS correct.
38
Debounce with GCD `GCD`
``` final class Debouncer { private let q = DispatchQueue(label: "deb"); private var work: DispatchWorkItem? func call(after d: TimeInterval, _ block:@escaping()->Void){ work?.cancel(); let w = DispatchWorkItem(block:block); work = w q.asyncAfter(deadline:.now()+d, execute:w) } } ```
39
Thread-safe dict pattern `GCD`
```swift final class SafeDict{ private var box:[K:V]=[:]; private let q=DispatchQueue(label:"rw", attributes:.concurrent) subscript(k:K)->V?{ get{ q.sync{box[k]} } set{ q.async(flags:.barrier){ self.box[k]=newValue } } } } ```
40
Background work after app bg `GCD`
Prefer BGTaskScheduler, background URLSession; avoid long main-queue work.
41
When pick GCD over async/await? `GCD`
Legacy interop, DispatchSource, precise queue control, OperationQueue integration.
42
what are the most common issues of GCD?
- Priority Inversion - Race conditions - Dead Lock
43
When I write this, what kind of queue I'm creating? `GCD` ``` private let q = DispatchQueue(label: "deb"); ```
By default, `DispatchQueue(label:)` creates a serial queue. Serial means only one task runs at a time, in the order you enqueue them. If you want a concurrent queue, you’d need to explicitly pass the attribute .concurrent: ``` let q = DispatchQueue(label: "deb", attributes: .concurrent) ```