Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using pthreads and callbacks

Status
Not open for further replies.

robUK2

Programmer
Mar 10, 2008
57
0
0
TH
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,

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;
}
 
hi,
working in inter-process comunication,
(probably with trhread is similar),
when a process "sleeps", you can send a signal()
with WAKE signal:
if the process does not receive signal, programs
continues after sleep statement;
if it receive signal WAKE or Ctrl-C (if it is running in console mode), the program jumps at signal (callback) routine, that you have declared.

ciao
vittorio
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top