From 6d95fd5fb8097da33fa0a96c6a14e6199c64610a Mon Sep 17 00:00:00 2001 From: Jan-Erik Rediger Date: Tue, 28 May 2024 12:49:26 +0200 Subject: [PATCH] pass data into thread --- backend/cmd/threads/main.ha | 7 ++++--- backend/vendor/hare-thread/thread/thread.ha | 23 ++++++++++++++------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/backend/cmd/threads/main.ha b/backend/cmd/threads/main.ha index e73b8aa..02dbddf 100644 --- a/backend/cmd/threads/main.ha +++ b/backend/cmd/threads/main.ha @@ -2,13 +2,14 @@ use types::c; use fmt; use thread; -fn thread_start() void = { - fmt::println("hello from another thread")!; +fn thread_start(data: nullable *opaque) void = { + let arg = data: *u32; + fmt::printfln("hello from another thread. you sent: {}", *arg)!; }; export fn main() void = { fmt::println("starting a thread")!; - let tid = thread::spawn(&thread_start)!; + let tid = thread::spawn(&thread_start, &42)!; fmt::println("joining")!; thread::join(tid)!; diff --git a/backend/vendor/hare-thread/thread/thread.ha b/backend/vendor/hare-thread/thread/thread.ha index b0b51ad..3b94830 100644 --- a/backend/vendor/hare-thread/thread/thread.ha +++ b/backend/vendor/hare-thread/thread/thread.ha @@ -3,15 +3,21 @@ use types::c; export type pthread_t = [8]u8; type pthread_attr_t = opaque; type pthread_fn = fn(nullable *opaque) nullable *opaque; -export type thread_fn = fn() void; +export type thread_fn = fn(nullable *opaque) void; @symbol("pthread_create") fn pthread_create(thread: nullable *pthread_t, attr: nullable *pthread_attr_t, start_routine: *pthread_fn, arg: nullable *opaque) int; @symbol("pthread_join") fn pthread_join(thread: pthread_t, nullable *nullable *opaque) int; @symbol("pthread_detach") fn pthread_detach(thread: pthread_t) int; -fn thread_spawn_wrapper(data: nullable *opaque) nullable *opaque = { - let f = data: *thread_fn; - f(); +type data_wrapper = struct { + f: *thread_fn, + data: nullable *opaque, +}; + +fn thread_spawn_wrapper(arg: nullable *opaque) nullable *opaque = { + let data = arg: *data_wrapper; + data.f(data.data); + free(data); return null; }; @@ -23,11 +29,14 @@ export type join_handle = struct { // spawn a thread // // returns a handle or an error -export fn spawn(f: *thread_fn) (join_handle | error) = { - let data = f: *opaque; +export fn spawn(f: *thread_fn, data: nullable *opaque) (join_handle | error) = { + let data: *data_wrapper = alloc(data_wrapper { + f = f, + data = data, + }); let tid: pthread_t = [0...]; - let ret = pthread_create(&tid, null, &thread_spawn_wrapper, f); + let ret = pthread_create(&tid, null, &thread_spawn_wrapper, data); if (ret != 0) { return error; };