Skip to content

Instantly share code, notes, and snippets.

@donn
Created November 17, 2019 15:08
Show Gist options
  • Save donn/76d62da999882a9e61ad638c049f3848 to your computer and use it in GitHub Desktop.
Save donn/76d62da999882a9e61ad638c049f3848 to your computer and use it in GitHub Desktop.
c thread pool future swift
// 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