Last active
November 28, 2022 09:36
-
-
Save oliverepper/eca0ab24c48c2240b1f9cff2b2f0010a to your computer and use it in GitHub Desktop.
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
/* | |
* This is all Eric Nieblers work, see: https://youtu.be/h-ExnuD6jms | |
*/ | |
import Foundation | |
protocol Receiver<T> { | |
associatedtype T | |
func setValue(_ value: T) | |
} | |
func calcInt() -> (any Receiver<Int>) -> Void { | |
return { r in | |
Thread { | |
r.setValue(42) | |
}.start() | |
} | |
} | |
struct ThenSender<T>: Receiver { | |
let p: any Receiver<T> | |
let next: (T) -> T | |
init(_ p: any Receiver<T>, _ next: @escaping (T) -> T) { | |
self.p = p | |
self.next = next | |
} | |
func setValue(_ value: T) { | |
p.setValue(next(value)) | |
} | |
} | |
func then<T>(_ task: @escaping (any Receiver<T>) -> Void, _ next: @escaping (T) -> T) -> (any Receiver<T>) -> Void { | |
return { p in | |
task(ThenSender(p, next)) | |
} | |
} | |
class Shared<T> { | |
var mtx = pthread_mutex_t() | |
var cv = pthread_cond_t() | |
var data: T! | |
init() { | |
pthread_mutex_init(&mtx, nil) | |
pthread_cond_init(&cv, nil) | |
} | |
} | |
struct Promise<T>: Receiver { | |
var shared: Shared<T> | |
func _set(_ value: T) { | |
pthread_mutex_lock(&shared.mtx) | |
shared.data = value | |
pthread_mutex_unlock(&shared.mtx) | |
pthread_cond_signal(&shared.cv) | |
} | |
func setValue(_ value: T) { | |
_set(value) | |
} | |
} | |
func sync_wait<T>(_ task: @escaping (any Receiver<T>) -> Void) -> T { | |
let shared = Shared<T>() | |
// start | |
task(Promise<T>(shared: shared)) | |
// get | |
func _get() { | |
pthread_mutex_lock(&shared.mtx) | |
while shared.data == nil { | |
pthread_cond_wait(&shared.cv, &shared.mtx) | |
} | |
pthread_mutex_unlock(&shared.mtx) | |
} | |
_get() | |
return shared.data | |
} | |
let start = calcInt() | |
let next = then(start, { i in return i / 2 }) | |
print("Value: \(sync_wait(next))") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment