Last active
March 4, 2022 23:56
-
-
Save opsJson/0b6ca1597acc6a80a722f7e3af0140a8 to your computer and use it in GitHub Desktop.
Easily async and resync any function, casts are automatically made. You can pass any number of arguments, and can get the return value. Easy interface for mutex.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <assert.h> | |
#include <pthread.h> | |
#include <stdarg.h> | |
#define thread_local _Thread_local | |
#ifndef THREAD_MAX | |
#define THREAD_MAX 50 | |
#endif | |
#ifndef MUTEX_MAX | |
#define MUTEX_MAX 50 | |
#endif | |
pthread_t t_id[THREAD_MAX] = {0}; | |
pthread_mutex_t mutex_id[MUTEX_MAX] = {0}; | |
size_t ThreadCount = 0; | |
size_t MutexCount = 0; | |
typedef pthread_t* thread; | |
#define FUNCTION void* | |
#define VARIABLE void* | |
thread async(FUNCTION function, ...) {} | |
#define async(x, ...) &t_id[ThreadCount]; { \ | |
void* thread(void *ignore) \ | |
{ \ | |
assert("THREAD MAX rechead!" && ThreadCount < THREAD_MAX); \ | |
x(__VA_ARGS__); \ | |
} \ | |
pthread_create(&t_id[ThreadCount++], NULL, thread, NULL); \ | |
} | |
thread asyncEx(VARIABLE var, FUNCTION function, ...) {} | |
#define asyncEx(var, x, ...) &t_id[ThreadCount]; { \ | |
void* thread(void *ignore) \ | |
{ \ | |
assert("THREAD MAX rechead!" && ThreadCount < THREAD_MAX); \ | |
var = x(__VA_ARGS__); \ | |
} \ | |
pthread_create(&t_id[ThreadCount++], NULL, thread, NULL); \ | |
} | |
#undef VARIABLE | |
#undef FUNCTION | |
void resync(thread id) {} | |
#define resync(x) pthread_join(*x, NULL) | |
#define MACRO void | |
MACRO thread_lock(int id) {} | |
#define thread_lock(id) \ | |
assert("MUTEX MAX rechead!" && MutexCount < MUTEX_MAX); \ | |
if (mutex_id[id] == 0) mutex_id[id] = PTHREAD_MUTEX_INITIALIZER; \ | |
pthread_mutex_lock(&(mutex_id[id])) | |
MACRO thread_unlock(int id) {} | |
#define thread_unlock(id) pthread_mutex_unlock(&mutex_id[id]) | |
#undef MACRO | |
/*/////////////////////////////////// | |
Testing: | |
///////////////////////////////////*/ | |
void foo(int count, ...) { | |
va_list args; | |
va_start(args, count); | |
while (count--) { | |
int i = va_arg(args, int); | |
printf("%i ", i); | |
} | |
printf("\n\n"); | |
} | |
int bar(char* msg, int n) { | |
int i; | |
for (i=0; i<n; i++) | |
printf("%s\n", msg); | |
return n * 2; | |
} | |
int main() { | |
thread t1 = async(foo, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); | |
thread t2 = async(bar, "foo!", 5); | |
int i; | |
thread t3 = asyncEx(i, bar, "bar!", 5); | |
resync(t1); | |
resync(t2); | |
resync(t3); | |
printf("returned value: %i\n", i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment