Skip to content

Instantly share code, notes, and snippets.

@alexdremov
Last active May 13, 2022 08:54
Show Gist options
  • Save alexdremov/d84bc914b02fe54fe629d0e61e64c9d0 to your computer and use it in GitHub Desktop.
Save alexdremov/d84bc914b02fe54fe629d0e61e64c9d0 to your computer and use it in GitHub Desktop.
class MyThread: Thread {
override func main() { // Thread's starting point
print("Hi from thread")
}
}
let thread = MyThread()
thread.start()
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
class MyThread: Thread {
...
func exit() {
waiter.leave()
Thread.exit()
}
...
}
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