Hello,
GCC C99
I have just created a simple program, as this is my first time with threads and callbacks.
However, I am wondering do I really need a callback. Can I just call the timeout_cb() function
after the sleep() as completed? Maybe I don't understand, why a callback is needed at all?
Just one more question. The time could be set for a long as 30 seconds. However, the task might
complete before then. Is there any way to stop the timer. As if the task has been completed before
the 30 seconds, I don't want the call back to be called at all? What is I need is stop_timer.
I was thinking is there anyway to stop the sleep once it has started?
Many thanks for any suggestions,
GCC C99
I have just created a simple program, as this is my first time with threads and callbacks.
However, I am wondering do I really need a callback. Can I just call the timeout_cb() function
after the sleep() as completed? Maybe I don't understand, why a callback is needed at all?
Just one more question. The time could be set for a long as 30 seconds. However, the task might
complete before then. Is there any way to stop the timer. As if the task has been completed before
the 30 seconds, I don't want the call back to be called at all? What is I need is stop_timer.
I was thinking is there anyway to stop the sleep once it has started?
Many thanks for any suggestions,
Code:
#include <pthread.h>
#include <stdio.h>
/* call back function - inform the user the time has expired */
void timeout_cb()
{
printf("=== your time is up ===\n");
}
/* Go to sleep for a period of seconds */
static void* g_start_timer(void *args)
{
/* function pointer */
void (*function_pointer)();
/* cast the seconds passed in to int and
* set this for the period to wait */
int seconds = *((int*) args);
printf("go to sleep for %d\n", seconds);
/* assign the address of the cb to the function pointer */
function_pointer = timeout_cb;
sleep(seconds);
/* call the cb to inform the user time is out */
(*function_pointer)();
pthread_exit(NULL);
}
int main()
{
pthread_t thread_id;
int seconds = 3;
int rc;
rc = pthread_create(&thread_id, NULL, g_start_timer, (void *) &seconds);
if(rc)
printf("=== Failed to create thread\n");
pthread_join(thread_id, NULL);
printf("=== End of Program - all threads in ===\n");
return 0;
}