0

I'm trying to implement in C. setTimeout and setInterval of javascript :

setTimeout(function(){ alert("Hello"); }, 3000);
setInterval(function(){ alert("Hello"); }, 3000);

i have read some related oveflow question, and here my attempt with pthread, i post a minimum example :

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

typedef struct timeCallback_s
{
    int    sec          ;
    void (*cb)(void*)   ;
    int    fInterval     ;
} timeCallback_t ;
static void* timeTimer(void *_t )
{
    timeCallback_t* t = (timeCallback_t*) _t ;

    int   sec         = t->sec ;
    void (*cb)(void*) = t->cb ;
    int   fInterval   = t->fInterval ;

    if ( fInterval==1 ) {
        while(1) {
            sleep(sec);
            (*cb)((void*)&sec);
        }
    }  else  {
        sleep(sec);
        (*cb)((void*)&sec);
    }
    pthread_exit(NULL);
}
void timeout_cb(void*_x)
{
    int x = *(int*)_x;
    printf("\n=== CALLBACK %d===\n",x);
}

main fuction

int main(void)
{
    timeCallback_t timer2;
    timer2.sec       = 1;
    timer2.cb        = timeout_cb ;
    timer2.fInterval = 1 ;

    pthread_t t2;
    pthread_create(&t2, NULL, timeTimer , (void *) &timer2);
    pthread_join(t2, NULL);

    timeCallback_t timer1 ;
    timer1.sec       = 5 ;
    timer1.cb        = timeout_cb ;
    timer1.fInterval = 0 ;

    pthread_t t1;
    pthread_create(&t1, NULL, timeTimer , (void *) &timer1 );
    pthread_join(t1, NULL);

    printf("\n=== End of Program - all threads in ===\n");

    return 0;
}

output is a deadlock :

other stack overflow question :

timer-and-pthreads-posix

pthread-timeout

can you help me ?

solution :

pthread_join(t2, NULL);
pthread_join(t1, NULL);

1 Answers1

0

You didn't specify what problem you are having. If it's that timer1 is never called, it's because you wait for t2 to exit before creating t1, and t2 never exits.

Move pthread_join(t2, NULL); down.

ikegami
  • 367,544
  • 15
  • 269
  • 518