关于libevent的事件持续化EV_READ | EV_PERSIST

关于事件的可持续化

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

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:git

  • Whenever the socket is ready for reading.github

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

翻译

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

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

任什么时候候事件的回调函数触发都会重置持续化事件中的超时状态。所以,若是的事件有EV_READ/EV_PERSIST而且设置了5秒超时,那么有两种状况会触发这个事件:oop

  1. 当socket能够进行读取的时候翻译

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

给个例子:

<?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);
}
相关文章
相关标签/搜索