Skip to content

Instantly share code, notes, and snippets.

@aprell
Created August 27, 2019 13:13
Show Gist options
  • Save aprell/33dd1dcf314f1bf329199d1891b19ec4 to your computer and use it in GitHub Desktop.
Save aprell/33dd1dcf314f1bf329199d1891b19ec4 to your computer and use it in GitHub Desktop.
Yet another task macro
// CFLAGS="-Wall -Wextra"
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct task {
void (*func)(void *);
void *args;
struct task *next;
} Task;
static Task *task_alloc(void (*func)(void *), void *args)
{
Task *task = (Task *)malloc(sizeof(Task));
if (!task) {
fprintf(stderr, "Warning: task_alloc failed\n");
return NULL;
}
task->func = func;
task->args = args;
task->next = NULL;
return task;
}
// Constructor for tasks
#define TASK(func, ...) \
({ \
struct func##_args *args = malloc(sizeof(struct func##_args)); \
if (!args) { \
fprintf(stderr, "Warning: TASK failed\n"); \
assert(false); \
} \
*args = (struct func##_args){ __VA_ARGS__ }; \
task_alloc(func, args); \
})
struct task_func_args {
int *answer;
};
void task_func(void *args)
{
assert(args != NULL);
int *answer = ((struct task_func_args *)args)->answer;
*answer = 42;
}
int main(void)
{
int answer;
Task *t = TASK(task_func, &answer);
// ...
t->func(t->args);
free(t->args);
free(t);
assert(answer == 42);
return 0;
}
@aprell
Copy link
Author

aprell commented May 28, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment