Last active
August 31, 2025 00:31
-
-
Save pookjw/6a36d4d506b75e386c2077b5eccd041f 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
| 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