#include <sys/cdefs.h>
__RCSID("$NetBSD: thrd.c,v 1.4 2019/09/10 22:34:19 kamil Exp $");
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <stdlib.h>
#include <time.h>
#include <threads.h>
struct __thrd_tramp_data {
thrd_start_t func;
void *arg;
};
static void *
__thrd_create_tramp(void *arg)
{
struct __thrd_tramp_data *cookie;
int ret;
_DIAGASSERT(arg != NULL);
cookie = (struct __thrd_tramp_data *)arg;
ret = (cookie->func)(cookie->arg);
free(cookie);
return (void *)(intptr_t)ret;
}
int
thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
{
struct __thrd_tramp_data *cookie;
int error;
_DIAGASSERT(thr != NULL);
_DIAGASSERT(func != NULL);
cookie = malloc(sizeof(*cookie));
if (cookie == NULL)
return thrd_nomem;
cookie->func = func;
cookie->arg = arg;
switch(pthread_create(thr, NULL, __thrd_create_tramp, cookie)) {
case 0:
return thrd_success;
case ENOMEM:
error = thrd_nomem;
break;
default:
error = thrd_error;
}
free(cookie);
return error;
}
thrd_t
thrd_current(void)
{
return pthread_self();
}
int
thrd_detach(thrd_t thr)
{
_DIAGASSERT(thr != NULL);
if (pthread_detach(thr) == 0)
return thrd_success;
return thrd_error;
}
int
thrd_equal(thrd_t t1, thrd_t t2)
{
_DIAGASSERT(t1 != NULL);
_DIAGASSERT(t2 != NULL);
return pthread_equal(t1, t2);
}
__dead void
thrd_exit(int res)
{
pthread_exit((void *)(intptr_t)res);
}
int
thrd_join(thrd_t thrd, int *res)
{
void *ptr;
_DIAGASSERT(thrd != NULL);
if (pthread_join(thrd, &ptr) == 0) {
if (res)
*res = (int)(intptr_t)ptr;
return thrd_success;
}
return thrd_error;
}
int
thrd_sleep(const struct timespec *duration, struct timespec *remaining)
{
_DIAGASSERT(duration != NULL);
switch (clock_nanosleep(CLOCK_MONOTONIC, TIMER_RELTIME, duration,
remaining)) {
case 0:
return 0;
case EINTR:
return -1;
default:
return -2;
}
}
void
thrd_yield(void)
{
sched_yield();
}