#include #include #include #include typedef struct { int delay; void* (*targetFunc)(void*); void* arg; } TimerParams; void* threadHelper(void* arg) { TimerParams* t = (TimerParams*)arg; sleep(t->delay); t->targetFunc(t->arg); free(t); return(0); // TODO: get the return value from the function? } int addTimer(int delay, void* (*targetFunc)(void*), void* arg) { printf("Adding a timer...\n"); TimerParams* t = (TimerParams*) malloc(sizeof(TimerParams)); t->delay = delay; t->targetFunc = targetFunc; t->arg = arg; pthread_t thread; return pthread_create(&thread, NULL, threadHelper, (void*)t); } //---- User interface code below here void* sayMessage(void* msg) { printf("%s\n", (char*)msg); return 0; } int main(int argc, char* argv[]) { addTimer(3, sayMessage, (void*)"This is the first message"); addTimer(3, sayMessage, (void*)"This is the second message"); addTimer(3, sayMessage, (void*)"I'm the last one!!!"); // Quit main while allowing other threads to finish up pthread_exit(NULL); }