c gcc program compiler
I have 3 files. main.c stop_watch.h and stop_watch.c
This program works. I call start_stopwatch. And it will be a callback in main.c timeout_cb () after time has passed. I also run this in a separate thread, since I do not want to block basically, since I will have different code that I need to run.
1) Seconds in g_start_timer always give garbage. I thought I might have solved this by creating a structure on the heap. In any case, I can solve it. I was thinking of creating a seconds element on the heap. But think it's killed
2) This program works fine, but if I comment on the line basically printf ("=== timeout_cb:% p \ n", timeout_cb); he will stack the dump.
3) when is the best time to free memory. I freed him mostly. But I worry if the memory is freed before the thread ends. This can cause a very unexpected result. I think I could use thread_join () to free memory after this call. However, I will need to return thead_id created in stop_watch.c, there is a way to return the thread_id that is created in stop_watch.c
Thanks so much for any suggestions,
main.c
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "stop_watch.h" /* call this when the time expires */ void timeout_cb() { printf("=== your time is up run some job here ===\n"); } int main() { struct data_struct *g_data_struct = (struct data_struct*) calloc(1, sizeof(*g_data_struct)); if(!g_data_struct) { printf("=== failed to allocate memory ===\n"); return 0; } g_data_struct->seconds = 3; g_data_struct->func_ptr = timeout_cb; // printf("=== timeout_cb: %p\n", timeout_cb); start_stopwatch(g_data_struct); // free(g_data_struct); printf("=== End of Program - all threads in ===\n"); pthread_exit(NULL); return 0; }
stop_watch.h
struct data_struct { int seconds; void (*func_ptr)(void); }; void start_stopwatch(struct data_struct *g_data_struct);
stop_watch.c
#include <stdio.h> #include <pthread.h> #include "stop_watch.h" static void* g_start_timer(void *args) { void (*function_pointer)(); int seconds = ((struct data_struct*) args)->seconds; function_pointer = ((struct data_struct*) args)->func_ptr; printf("=== go to sleep for %d\n", seconds); sleep(seconds); (void) (*function_pointer)(); pthread_exit(NULL); return 0; } void start_stopwatch(struct data_struct *g_data_struct) { pthread_t thread_id; int rc; int seconds = g_data_struct->seconds; printf("=== start_stopwatch(): %d\n", seconds); rc = pthread_create(&thread_id, NULL, g_start_timer, (void *) &g_data_struct); if(rc) printf("=== Failed to create thread\n"); }