在C中模拟javascript的setTimeout和setInterval

simulate setTimeout and setInterval of javascript in C

我正在尝试用 C 实现。 javascript 的 setTimeout 和 setInterval :

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

我已经阅读了一些相关的溢出问题,并且 这是我对 pthread 的尝试,我 post 一个最小的例子:

#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);
}

主要功能

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;
}

输出是一个死锁:

其他堆栈溢出问题:

timer-and-pthreads-posix

pthread-timeout

你能帮帮我吗?

解决方案:

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

您没有说明遇到的问题。如果从未调用 timer1,那是因为您在创建 t1 之前等待 t2 退出,而 t2 从未退出。

下移 pthread_join(t2, NULL);