Skip to content

Instantly share code, notes, and snippets.

@Lokno
Last active September 27, 2024 21:34
Show Gist options
  • Select an option

  • Save Lokno/af74fc97add9b4e413aca4b516751813 to your computer and use it in GitHub Desktop.

Select an option

Save Lokno/af74fc97add9b4e413aca4b516751813 to your computer and use it in GitHub Desktop.
Single Header Library for Simple Cross-Platform Threading
// Single Header Library for Simple Cross-Platform Threading
//
// sthread_handle handle;
// STHREAD_CREATE(handle, Func, &argument );
// STHREAD_JOIN(handle);
// STHREAD_DESTROY(handle);
//
// STHREAD_RETVAL Func( void* pArguments )
// {
// // Do Work Here
// STHREAD_END
// }
#if defined(__unix__) || defined(__unix) || \
(defined(__APPLE__) && defined(__MACH__))
#define POSIX
#endif
#ifdef POSIX
#include <pthread.h>
#else
#include <windows.h>
#endif
#include <stdlib.h>
typedef struct
{
#ifdef POSIX
pthread_t tid;
#else
HANDLE hThread;
unsigned int threadID;
#endif
}sthread_data;
typedef sthread_data* sthread_handle;
#ifdef POSIX
#define STHREAD_RETVAL void*
#else
#define STHREAD_RETVAL unsigned __stdcall
#endif
#ifdef POSIX
#define STHREAD_END pthread_exit(NULL);
#else
#define STHREAD_END _endthreadex( 0 ); return 0;
#endif
#ifdef POSIX
#define STHREAD_CREATE(handle, start_routine, arg_ptr) { \
handle = (sthread_data*)malloc(sizeof(sthread_data)); \
pthread_create(&handle->tid, NULL, start_routine, arg_ptr); \
}
#else
#define STHREAD_CREATE(handle, start_routine, arg_ptr) { \
handle = (sthread_data*)malloc(sizeof(sthread_data)); \
handle->hThread = (HANDLE)_beginthreadex( NULL, 0, &start_routine, arg_ptr, 0, &handle->threadID ); \
}
#endif
#ifdef POSIX
#define STHREAD_IS_RUNNING(handle) (pthread_kill(handle->tid, 0) == 0)
#else
#define STHREAD_IS_RUNNING(handle) (WaitForSingleObject( handle->hThread, 0 ) == WAIT_TIMEOUT)
#endif
#ifdef POSIX
#define STHREAD_JOIN(handle) { \
pthread_join(handle->tid, NULL); \
}
#else
#define STHREAD_JOIN(handle) { \
WaitForSingleObject( handle->hThread, INFINITE ); \
}
#endif
#ifdef POSIX
#define STHREAD_DESTROY(handle) { \
free(handle); \
handle = NULL; \
}
#else
#define STHREAD_DESTROY(handle) { \
CloseHandle( handle->hThread ); \
free(handle); \
handle = NULL; \
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment