tomo/stdlib/threads.c

78 lines
1.8 KiB
C
Raw Normal View History

2024-08-11 11:47:34 -07:00
// Logic for the Thread type, representing a pthread
#include <ctype.h>
#include <err.h>
2024-11-03 19:37:48 -08:00
#include <fcntl.h>
2024-08-11 11:47:34 -07:00
#include <gc.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/param.h>
2024-11-03 13:21:40 -08:00
#include <sys/random.h>
2024-08-11 11:47:34 -07:00
#include "arrays.h"
2024-10-27 09:58:37 -07:00
#include "datatypes.h"
2024-11-03 19:37:48 -08:00
#include "rng.h"
2024-09-02 15:47:39 -07:00
#include "text.h"
2024-09-24 11:54:22 -07:00
#include "threads.h"
2024-08-11 11:47:34 -07:00
#include "types.h"
#include "util.h"
2024-11-03 13:21:40 -08:00
static void *run_thread(Closure_t *closure)
{
2024-11-03 19:37:48 -08:00
uint8_t *random_bytes = GC_MALLOC_ATOMIC(40);
getrandom(random_bytes, 40, 0);
Array_t rng_seed = {.length=40, .data=random_bytes, .stride=1, .atomic=1};
default_rng = RNG$new(rng_seed);
2024-11-03 13:21:40 -08:00
((void(*)(void*))closure->fn)(closure->userdata);
return NULL;
}
2024-09-24 11:54:22 -07:00
public Thread_t Thread$new(Closure_t fn)
2024-08-11 11:47:34 -07:00
{
2024-09-24 11:54:22 -07:00
Thread_t thread = new(pthread_t);
2024-11-03 13:21:40 -08:00
Closure_t *doop = new(Closure_t, .fn=fn.fn, .userdata=fn.userdata);
pthread_create(thread, NULL, (void*)run_thread, doop);
2024-08-11 11:47:34 -07:00
return thread;
}
2024-09-24 11:54:22 -07:00
public void Thread$join(Thread_t thread)
2024-08-11 11:47:34 -07:00
{
pthread_join(*thread, NULL);
}
2024-09-24 11:54:22 -07:00
public void Thread$cancel(Thread_t thread)
2024-08-11 11:47:34 -07:00
{
pthread_cancel(*thread);
}
2024-09-24 11:54:22 -07:00
public void Thread$detach(Thread_t thread)
2024-08-11 11:47:34 -07:00
{
pthread_detach(*thread);
}
2024-11-29 09:55:14 -08:00
Text_t Thread$as_text(const void *thread, bool colorize, const TypeInfo_t*)
2024-08-11 11:47:34 -07:00
{
if (!thread) {
return colorize ? Text("\x1b[34;1mThread\x1b[m") : Text("Thread");
2024-08-11 11:47:34 -07:00
}
2024-11-29 09:55:14 -08:00
return Text$format(colorize ? "\x1b[34;1mThread(%p)\x1b[m" : "Thread(%p)", *(Thread_t**)thread);
}
static bool Thread$is_none(const void *obj, const TypeInfo_t*)
{
return *(Thread_t*)obj == NULL;
2024-08-11 11:47:34 -07:00
}
public const TypeInfo_t Thread$info = {
2024-09-24 11:54:22 -07:00
.size=sizeof(Thread_t), .align=__alignof(Thread_t),
2024-11-29 09:55:14 -08:00
.metamethods={
.as_text=Thread$as_text,
.is_none=Thread$is_none,
},
2024-08-11 11:47:34 -07:00
};
// vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1,\:0