Skip to content

Instantly share code, notes, and snippets.

@io12
Created October 18, 2017 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save io12/e5de4e1cd3342805407765e4fdc41740 to your computer and use it in GitHub Desktop.
Save io12/e5de4e1cd3342805407765e4fdc41740 to your computer and use it in GitHub Desktop.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef void *(ThunkFunc)(void *);
typedef struct thunk Thunk;
struct thunk {
void *result;
ThunkFunc *func;
void *param;
};
void *force_thunk(Thunk *thunk)
{
if (thunk->result == NULL) {
thunk->result = thunk->func(thunk->param);
}
return thunk->result;
}
void mkthunk_from_ref(Thunk *thunk, ThunkFunc *func, void *param)
{
thunk->result = NULL;
thunk->func = func;
thunk->param = param;
}
void *thunk_func(void *param)
{
int *p;
(void) param;
puts("foo");
p = malloc(sizeof(int));
*p = 10;
return p;
}
int main(void)
{
Thunk thunk;
mkthunk_from_ref(&thunk, thunk_func, NULL);
puts("bar");
printf("%d\n", *(int *) force_thunk(&thunk));
printf("%d\n", *(int *) force_thunk(&thunk));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment