Created
August 27, 2019 13:13
-
-
Save aprell/33dd1dcf314f1bf329199d1891b19ec4 to your computer and use it in GitHub Desktop.
Yet another task macro
This file contains 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
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://github.com/aprell/compiler-potpourri/blob/master/openmp/task.h