c - 用C模拟javascript的setTimeout和setInterval

标签 c timer pthreads

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

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

我已经阅读了一些相关的overflow问题,并且 这是我对 pthread 的尝试,我发布了一个最小的示例:

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

关于c - 用C模拟javascript的setTimeout和setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57123224/

相关文章:

c++ - C/C++ 中的 Aho-Corasick 算法(十六进制)

c - C语言中如何让数组只接受数字?

java - 安排定期运行方法´

multithreading - 创建一个将一直阻塞直到被n/2个以上线程调用的函数(伪代码)

Linux 线程和进程 - CPU 亲和性

c - 在 Ubuntu 16.04 上构建 QEMU 版本 0.15.1 失败

php - 在编译期间检测 PHP 是否正在使用给定的扩展名进行编译

jquery - 我如何知道使用 Jquery 或 Javascript 加载当前页面多长时间?

go - 通过 http 启动/停止和处理自定义调度程序

c - 服务器中的 Leader/Follower pthread 实现