Last active
October 30, 2019 11:54
-
-
Save nuclearace/b2c087e114d4b792cd54cb675e15219c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| import Playground | |
| private let lock = DispatchSemaphore(value: 1) | |
| private let queue = DispatchQueue(label: "worker", attributes: .concurrent) | |
| private let nWorkers = 5 | |
| private let stopAt = 1 << 30 | |
| private var i = 33550336 | |
| private var running = nWorkers | |
| func calculatePerfect() { | |
| queue.async { | |
| lock.wait() | |
| let n = i | |
| i += 1 | |
| guard n < stopAt else { | |
| running -= 1 | |
| if running == 0 { | |
| exit(0) | |
| } | |
| lock.signal() | |
| return | |
| } | |
| lock.signal() | |
| if n.isMultiple(of: 100_000) { | |
| print("Passing \(n)") | |
| } | |
| if n.isPerfectNumber { | |
| print("\(n) is perfect") | |
| } | |
| calculatePerfect() | |
| } | |
| } | |
| for _ in 0..<nWorkers { | |
| calculatePerfect() | |
| } | |
| dispatchMain() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment