Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created March 7, 2021 17:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/fb65510f42e315f24859cd5a24efae4f to your computer and use it in GitHub Desktop.
Save robertmryan/fb65510f42e315f24859cd5a24efae4f to your computer and use it in GitHub Desktop.
// The following results in thread explosion:
for idx in 0..<10_000 {
concurrentQueue.async(group: group) {
self.something.n += idx
}
}
// We would instead do
concurrentQueue.async {
DispatchQueue.concurrentPerform(iterations: 10_000) { idx in
self.something.n += idx
}
}
@robertmryan
Copy link
Author

By using concurrentPerform, the number of GCD worker threads is limited to the number of cores on the device.

@robertmryan
Copy link
Author

robertmryan commented Mar 10, 2021

Needless to say, this isn’t thread-safe operation. I’m just showing how to avoid thread issue explosion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment