我正在尝试用 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;
}
输出是死锁:
其他堆栈溢出问题:
你能帮我吗?
解决方案:
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/