Created
October 18, 2017 00:17
-
-
Save io12/e5de4e1cd3342805407765e4fdc41740 to your computer and use it in GitHub Desktop.
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 <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