Skip to content

Instantly share code, notes, and snippets.

@pookjw
Last active August 31, 2025 00:31
Show Gist options
  • Select an option

  • Save pookjw/6a36d4d506b75e386c2077b5eccd041f to your computer and use it in GitHub Desktop.

Select an option

Save pookjw/6a36d4d506b75e386c2077b5eccd041f to your computer and use it in GitHub Desktop.
private import Foundation
private import _DarwinFoundation3.pthread
fileprivate final class Box<U> {
let value: U
init(value: U) {
self.value = value
}
}
fileprivate func executeBlock<T>(_ block: @escaping () throws -> T) async throws -> T {
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<T, any Error>) in
executeBlock {
do {
let result = try block()
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
}
}
fileprivate func executeBlock(_ block: @escaping () -> Void) {
withUnsafeTemporaryAllocation(of: pthread_t.self, capacity: 1) { threadPointer in
let box = Box(value: block)
let castedThreadPointer = UnsafeMutableRawPointer(threadPointer.baseAddress.unsafelyUnwrapped)
.assumingMemoryBound(to: pthread_t?.self)
pthread_create(
castedThreadPointer,
nil,
{ boxPointer in
return autoreleasepool {
let box = unsafeBitCast(boxPointer, to: Box<() -> Void>.self)
box.value()
Unmanaged.passUnretained(box).release()
return nil
}
},
Unmanaged.passRetained(box).toOpaque()
)
pthread_detach(castedThreadPointer.pointee.unsafelyUnwrapped)
}
}
fileprivate func executeBlock<T>(_ block: @escaping () -> T) async -> T {
return await withCheckedContinuation { (continuation: CheckedContinuation<T, Never>) in
executeBlock {
let result = block()
continuation.resume(returning: result)
}
}
}
@main
struct MyScript {
static func main() async {
await executeBlock {
print(pthread_self())
// throw CancellationError()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment