1
Fork 0

pass data into thread

This commit is contained in:
Jan-Erik Rediger 2024-05-28 12:49:26 +02:00
parent 65d3f8260c
commit 6d95fd5fb8
2 changed files with 20 additions and 10 deletions

View file

@ -2,13 +2,14 @@ use types::c;
use fmt; use fmt;
use thread; use thread;
fn thread_start() void = { fn thread_start(data: nullable *opaque) void = {
fmt::println("hello from another thread")!; let arg = data: *u32;
fmt::printfln("hello from another thread. you sent: {}", *arg)!;
}; };
export fn main() void = { export fn main() void = {
fmt::println("starting a thread")!; fmt::println("starting a thread")!;
let tid = thread::spawn(&thread_start)!; let tid = thread::spawn(&thread_start, &42)!;
fmt::println("joining")!; fmt::println("joining")!;
thread::join(tid)!; thread::join(tid)!;

View file

@ -3,15 +3,21 @@ use types::c;
export type pthread_t = [8]u8; export type pthread_t = [8]u8;
type pthread_attr_t = opaque; type pthread_attr_t = opaque;
type pthread_fn = fn(nullable *opaque) nullable *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_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_join") fn pthread_join(thread: pthread_t, nullable *nullable *opaque) int;
@symbol("pthread_detach") fn pthread_detach(thread: pthread_t) int; @symbol("pthread_detach") fn pthread_detach(thread: pthread_t) int;
fn thread_spawn_wrapper(data: nullable *opaque) nullable *opaque = { type data_wrapper = struct {
let f = data: *thread_fn; f: *thread_fn,
f(); 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; return null;
}; };
@ -23,11 +29,14 @@ export type join_handle = struct {
// spawn a thread // spawn a thread
// //
// returns a handle or an error // returns a handle or an error
export fn spawn(f: *thread_fn) (join_handle | error) = { export fn spawn(f: *thread_fn, data: nullable *opaque) (join_handle | error) = {
let data = f: *opaque; let data: *data_wrapper = alloc(data_wrapper {
f = f,
data = data,
});
let tid: pthread_t = [0...]; 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) { if (ret != 0) {
return error; return error;
}; };