Created
November 17, 2019 15:08
-
-
Save donn/76d62da999882a9e61ad638c049f3848 to your computer and use it in GitHub Desktop.
c thread pool future swift
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
// attempted to replace GCD but it turns out GCD was not in fact broken so uh Linux | |
import Foundation | |
import CThreadPool | |
var pool: threadpool? | |
public class Future { | |
private var semaphore: DispatchSemaphore | |
private var store: Any? | |
private var executor: () -> Any | |
init(executor: @escaping () -> Any) { | |
self.semaphore = DispatchSemaphore(value: 0) | |
self.executor = executor | |
if pool == nil { | |
pool = thpool_init(CInt( | |
ProcessInfo.processInfo.environment["FAULT_THREADS"] ?? "" | |
) ?? 64) | |
} | |
let _ = thpool_add_work(pool!, { | |
pointer in | |
let this = Unmanaged<Future>.fromOpaque(pointer!).takeUnretainedValue() | |
this.store = this.executor() | |
this.semaphore.signal() | |
}, Unmanaged.passUnretained(self).toOpaque()) | |
} | |
public var value: Any { | |
self.semaphore.wait() | |
let value = store! | |
return value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment