diff --git a/examples/threads.janet b/examples/threads.janet index 9e379d9b..4550c73f 100644 --- a/examples/threads.janet +++ b/examples/threads.janet @@ -1,18 +1,24 @@ (defn worker-main [parent] - (def name (thread/receive parent)) + (def name (:receive parent)) + (def interval (:receive parent)) (for i 0 10 - (os/sleep 1) - (print "thread " name " wakeup no. " i)) - (thread/send parent :done)) + (os/sleep interval) + (printf "thread %s wakeup no. %d\n" name i)) + (:send parent :done)) (defn make-worker - [name] - (-> (thread/new) (thread/send worker-main) (thread/send name))) + [name interval] + (-> (thread/new) + (:send worker-main) + (:send name) + (:send interval))) -(def bob (make-worker "bob")) -(os/sleep 0.5) -(def joe (make-worker "joe")) +(def bob (make-worker "bob" 0.2)) +(def joe (make-worker "joe" 0.3)) +(def sam (make-worker "joe" 0.5)) -(thread/receive bob) -(thread/receive joe) +# Receive out of order +(:receive bob) +(:receive sam) +(:receive joe) diff --git a/src/core/thread.c b/src/core/thread.c index a0020474..75ef9993 100644 --- a/src/core/thread.c +++ b/src/core/thread.c @@ -188,11 +188,13 @@ static int thread_mark(void *p, size_t size) { return 0; } +static Janet janet_thread_getter(void *p, Janet key); + static JanetAbstractType Thread_AT = { "core/thread", thread_gc, thread_mark, - NULL, + janet_thread_getter, NULL, NULL, NULL, @@ -318,6 +320,18 @@ static Janet cfun_thread_receive(int32_t argc, Janet *argv) { return out; } +static const JanetMethod janet_thread_methods[] = { + {"send", cfun_thread_send}, + {"receive", cfun_thread_receive}, + {NULL, NULL} +}; + +static Janet janet_thread_getter(void *p, Janet key) { + (void) p; + if (!janet_checktype(key, JANET_KEYWORD)) janet_panicf("expected keyword method"); + return janet_getmethod(janet_unwrap_keyword(key), janet_thread_methods); +} + static const JanetReg threadlib_cfuns[] = { { "thread/new", cfun_thread_new,