Skip to content

Instantly share code, notes, and snippets.

@menangen
Last active December 27, 2021 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save menangen/b86d391c72724c300545369982d550e6 to your computer and use it in GitHub Desktop.
Save menangen/b86d391c72724c300545369982d550e6 to your computer and use it in GitHub Desktop.
Dispatch Timer
//
// main.swift
// runLoop
//
// Created by menangen on 27.12.2021.
//
import Foundation
extension Thread {
var number: String {
"\(value(forKeyPath: "private.seqNum")!)"
}
}
actor AtomicStorage {
private var storage: [Int: String]
init() {
print("init actor thread: \(Thread.current.number)")
self.storage = [:]
}
func get(_ key: Int) -> String? {
storage[key]
}
func set(_ key: Int, value: String) {
storage[key] = value + ", actor thread: \(Thread.current.number)"
}
var allValues: [Int: String] {
print("allValues actor thread: \(Thread.current.number)")
return storage
}
}
Task {
print("Hello, Task!")
await Task.sleep(1_000_000_000)
print("Task thread:", Thread.current.number)
let storage = AtomicStorage()
await withTaskGroup(of: Void.self) { group in
for i in 0..<10 {
group.addTask {
await storage.set(i, value: "caller thread: \(Thread.current.number)")
}
}
}
for (k, v) in await storage.allValues {
print(k, v)
}
}
sleep(2)
//
// main.swift
// runLoop
//
// Created by menangen on 09.12.2021.
//
import Foundation
import Dispatch
let q = DispatchQueue(label: "Timer")
let delay : DispatchTime = .now() + .seconds(1)
let timeoutTimer = DispatchSource.makeTimerSource(queue: q)
timeoutTimer.setEventHandler {
print("setEventHandler", Thread.current)
usleep(500000)
}
timeoutTimer.schedule(deadline: delay, repeating: 0.2, leeway: .microseconds(50))
print("timeoutTimer.resume", timeoutTimer.resume())
sleep(3)
timeoutTimer.cancel()
import Foundation
let group = DispatchGroup()
class WriterThread: Thread {
var counter: UInt32 = 0
var isRunning = true
override func cancel() { isRunning = false }
override func main() {
repeat {
print("Hello, Thread!", Thread.current)
Thread.sleep(forTimeInterval: 1)
counter += 1
if counter > 5 { self.cancel() }
} while isRunning
print("Leaving")
group.leave()
}
}
group.enter()
let a = WriterThread()
a.start()
group.wait()
import Foundation
class WriterThread: Operation {
var counter: UInt32 = 0
override func main() {
var isRunning = true
repeat {
print("Hello, Thread!", Thread.current)
Thread.sleep(forTimeInterval: 1)
counter += 1
if counter > 5 { isRunning = false }
} while isRunning
}
}
let opQ = OperationQueue()
opQ.maxConcurrentOperationCount = 1
opQ.addOperations([WriterThread(), WriterThread()], waitUntilFinished: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment