Last active
May 13, 2022 08:54
-
-
Save alexdremov/d84bc914b02fe54fe629d0e61e64c9d0 to your computer and use it in GitHub Desktop.
This file contains 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
class MyThread: Thread { | |
override func main() { // Thread's starting point | |
print("Hi from thread") | |
} | |
} | |
let thread = MyThread() | |
thread.start() |
This file contains 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
class MyThread: Thread { | |
let waiter = DispatchGroup() | |
override func start() { | |
waiter.enter() | |
super.start() | |
} | |
override func main() { | |
task() | |
waiter.leave() | |
} | |
func task() { | |
print("Hi from thread") | |
} | |
func join() { | |
waiter.wait() | |
} | |
} | |
let thread = MyThread() | |
thread.start() | |
thread.join() // Waits for thread completion |
This file contains 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
class MyThread: Thread { | |
... | |
func exit() { | |
waiter.leave() | |
Thread.exit() | |
} | |
... | |
} |
This file contains 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
class MyThread: Thread { | |
let waiter = DispatchGroup() | |
override func start() { | |
waiter.enter() | |
super.start() | |
} | |
override func main() { | |
task() | |
waiter.leave() | |
} | |
func exit() { | |
waiter.leave() | |
Thread.exit() | |
} | |
func task() { | |
let start = Date.now | |
for _ in 0...100500 { | |
if isCancelled { | |
let seconds = Double(Date.now.timeIntervalSince(start)) | |
print("Cancelled after \(seconds) seconds") | |
exit() | |
} | |
Thread.sleep(forTimeInterval: 0.01) // Long task | |
} | |
} | |
func join() { | |
waiter.wait() | |
} | |
} | |
let thread = MyThread() | |
DispatchQueue.global().asyncAfter( | |
deadline: .now().advanced(by: .seconds(5))) { | |
thread.cancel() | |
} | |
thread.start() | |
thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment