1
0
mirror of https://github.com/janet-lang/janet synced 2024-12-27 08:50:27 +00:00

Add thread example.

Also remove reference to pthread_t in the JanetThread structure.
This commit is contained in:
Calvin Rose 2019-12-01 20:47:22 -06:00
parent 6a763aac95
commit 8f31a53276
3 changed files with 20 additions and 4 deletions

18
examples/threads.janet Normal file
View File

@ -0,0 +1,18 @@
(defn worker-main
[parent]
(def name (thread/receive parent))
(for i 0 10
(os/sleep 1)
(print "thread " name " wakeup no. " i))
(thread/send parent :done))
(defn make-worker
[name]
(-> (thread/new make-image-dict) (thread/send worker-main) (thread/send name)))
(def bob (make-worker "bob"))
(os/sleep 0.5)
(def joe (make-worker "joe"))
(thread/receive bob)
(thread/receive joe)

View File

@ -192,7 +192,6 @@ static JanetThread *janet_make_thread(JanetThreadShared *shared, JanetTable *dic
thread->shared = shared; thread->shared = shared;
thread->kind = who; thread->kind = who;
thread->dict = dict; thread->dict = dict;
thread->handle = NULL;
return thread; return thread;
} }
@ -213,7 +212,6 @@ static int thread_worker(JanetThreadShared *shared) {
/* Create self thread */ /* Create self thread */
JanetThread *thread = janet_make_thread(shared, dict, JANET_THREAD_SELF); JanetThread *thread = janet_make_thread(shared, dict, JANET_THREAD_SELF);
thread->handle = handle;
Janet threadv = janet_wrap_abstract(thread); Janet threadv = janet_wrap_abstract(thread);
/* Unmarshal the function */ /* Unmarshal the function */
@ -251,7 +249,8 @@ static void *janet_pthread_wrapper(void *param) {
static void janet_thread_start_child(JanetThread *thread) { static void janet_thread_start_child(JanetThread *thread) {
JanetThreadShared *shared = thread->shared; JanetThreadShared *shared = thread->shared;
int error = pthread_create(&thread->handle, NULL, janet_pthread_wrapper, shared); pthread_t handle;
int error = pthread_create(&handle, NULL, janet_pthread_wrapper, shared);
if (error) { if (error) {
thread->shared = NULL; /* Prevent GC from trying to mess with shared memory here */ thread->shared = NULL; /* Prevent GC from trying to mess with shared memory here */
janet_shared_destroy(shared); janet_shared_destroy(shared);

View File

@ -956,7 +956,6 @@ struct JanetThreadShared {
JanetChannel child; JanetChannel child;
}; };
struct JanetThread { struct JanetThread {
pthread_t handle;
JanetThreadShared *shared; JanetThreadShared *shared;
JanetTable *dict; JanetTable *dict;
enum { enum {