ev_timer的怪异超时

问题描述 投票:1回答:1

最近,我正在尝试使用线程代码libev,我刚刚发现计时器总是在60秒左右结束,无论您将其设置为低于60秒。我不确定是什么原因造成的,但我尝试过使代码最短。

1-调用一些io_init和io_start

2-创建将调用ev_loop的新线程

3-创建具有5秒钟超时的计时器

4-等待线程完成然后主函数结束

#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <ev.h>

void iocb(struct ev_loop *loop, ev_io *watcher, int flag){}

void tcb(struct ev_loop *loop, ev_timer *watcher, int flag){
    exit(0);
}

void *loop_starter(void *loop){
    ev_loop(loop, 0);
}

int main(){
    struct ev_loop *loop = ev_default_loop(0);

    ev_io evio;
    ev_io_init(&evio, iocb, 0, EV_READ);
    ev_io_start(loop, &evio);

    pthread_t pid;
    pthread_create(&pid, 0, loop_starter, loop);
    usleep(100000); /* let's be sure it entered inside ev_loop */

    ev_timer evt;
    ev_timer_init(&evt, tcb, 5, 0);
    ev_timer_start(loop, &evt);

    pthread_join(pid, 0);
}

当我用time ./a.out运行此代码时,我得到

real 0m59.805s
user 0m0.000s
sys 0m0.002s

不是应该在5秒后结束吗?为什么我得到的结果不是5秒?

c io pthreads libev
1个回答
0
投票

我们需要实现线程互斥或libev的ev_async函数。这是使用ev_async

的示例代码
#include <stdlib.h>
#include <pthread.h>
#include <ev.h>

void iocb(struct ev_loop *loop, ev_io *watcher, int flag){}

void tcb(struct ev_loop *loop, ev_timer *watcher, int flag){
    exit(0);
}

void *loop_starter(void *loop){
    ev_loop(loop, 0);
}

void async_cb(struct ev_loop *loop, ev_async *watcher, int flag){
    ev_timer *evt = malloc(sizeof(ev_timer));
    ev_timer_init(evt, tcb, 5, 0);
    ev_timer_start(loop, evt);
}

int main(){
    struct ev_loop *loop = ev_default_loop(0);
    ev_async async_w;
    ev_async_init(&async_w, async_cb);
    ev_async_start(loop, &async_w);

    ev_io evio;
    ev_io_init(&evio, iocb, 0, EV_READ);
    ev_io_start(loop, &evio);

    pthread_t pid;
    pthread_create(&pid, 0, loop_starter, loop);
    /* we don't need sleep more because */
    /* async_cb will be called from ev_loop */

    ev_async_send(loop, &async_w);

    pthread_join(pid, 0);
}

time ./a.out

real 0m5.003s
user 0m0.002s
sys 0m0.000s
© www.soinside.com 2019 - 2024. All rights reserved.