utilitiec/src/threading/os_thread.c

89 lines
1.8 KiB
C
Raw Normal View History

2024-06-13 15:28:21 +02:00
#include "os_thread.h"
#include <stdlib.h>
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <pthread.h>
int OSThread_Create(os_thread_t* destination, ThreadFunction subroutine, void* arg)
{
return pthread_create(destination, NULL, subroutine, arg);
}
int OSThread_Kill(os_thread_t* thread)
{
return pthread_cancel(*thread);
}
int OSThread_Join(os_thread_t* thread, void** thread_return)
{
return pthread_join(*thread, thread_return);
}
int OSThread_Destroy(os_thread_t* thread)
{
(void) thread;
return EXIT_SUCCESS;
}
#elif defined _WIN32
struct CaptureReturnArgument {
ThreadFunction subroutine;
void* arg;
void** return_value_storage;
};
static void capture_return(struct CaptureReturnArgument* a)
{
a.return_value_storage[0] = a->subroutine(a->arg);
return;
}
int OSThread_Create(os_thread_t* destination, ThreadFunction subroutine, void* arg)
{
destination->return_value_storage = malloc(sizeof(void*));
if (destination->return_value_storage == NULL) {
return ENOMEM;
}
destination->return_value_storage[0] = NULL;
destination->handle = CreateThread(
THREAD_ALL_ACCESS, // Security
0, // default stack size
capture_return, // start address
arg, // argument
0, // start immediately
NULL // thread id receeiver
);
if (destination->handle == NULL) {
return GetLastError();
}
return EXIT_SUCCESS;
}
int OSThread_Kill(os_thread_t* thread)
{
return 1 == TerminateThread(
thread->thread_handle,
0 // exit code
);
}
int OSThread_Join(os_thread_t* thread, void** thread_return)
{
WaitForSingleObject(thread->thread_handle, INFINITE);
thread_return[0] = thread->return_value_storage[0];
return EXIT_SUCCESS;
}
int OSThread_Destroy(os_thread_t* thread)
{
free(thread->return_value_storage);
CloseHandle(thread->thread_handle);
}
#endif