关于事件的可持续化

从网上找的内容,可以看下github中的一本book,点击下面的连接就ok了。
github-libevent_book引用其中的话

About Event Persistence
By default, whenever a pending event becomes active (because its fd is ready to read or write, or because its timeout expires), it becomes non-pending right before its callback is executed. Thus, if you want to make the event pending again, you can call event_add() on it again from inside the callback function.
If the EV_PERSIST flag is set on an event, however, the event is persistent. This means that event remains pending even when its callback is activated. If you want to make it non-pending from within its callback, you can call event_del() on it.
The timeout on a persistent event resets whenever the event’s callback runs. Thus, if you have an event with flags EV_READ|EV_PERSIST and a timeout of five seconds, the event will become active:

  • Whenever the socket is ready for reading.

  • Whenever five seconds have passed since the event last became active.

翻译

可能有不对的地方,欢迎指正

关于事件的持续化
默认情况下,任何时候一个挂起的事件被激活(因为他的fd准备好了读或者写,或者因为他的超时过期了),它会在回调函数执行之前变为非挂起。如果你想让事件再次挂起,你需要在回调函数内部调用event_add()
如果一个事件被设置了EV_PERSIST,那么这个事件就是持续化的,意思就是这个事件会保持挂起状态,即使回调函数被执行。如果你想让它变为非挂起状态,可以在回调函数中调用event_del()

任何时候事件的回调函数触发都会重置持续化事件中的超时状态。因此,如果的事件有EV_READ/EV_PERSIST并且设置了5秒超时,那么有两种情况会触发这个事件:

  1. 当socket可以进行读取的时候

  2. 当5s超时到期的时候

给个例子:

<?php
$base = event_base_new();
$event = event_new();

event_set($event,STDIN,EV_READ | EV_PERSIST,'print_line',[$event,$base]);

event_base_set($event,$base);
event_add($event,5000000);
event_base_loop($base);

function print_line($fd, $events, $arg)
{
    // 5秒超时会自动输出1,每次执行了read后,超时会被重置
    echo 1;
    static $max_requests = 0;
    $max_requests++;
    if ($max_requests == 10) {
        // $arg[1] = $base
        event_base_loopexit($arg[1]);
    }
    // 打印输出
    echo  fgets($fd);
}

jaysun
507 声望25 粉丝

Code is law