事件循环,IO复用,还是理解深刻一点好。

比较LIBEV和PYEV,发现PYTHON库只是对LIBEV作了简单的语法转换。

到了这个层次,就一个字:DIAO!!!

libev的C版:

#include <ev.h>
#include <stdio.h>

ev_io stdin_watcher;
ev_timer timeout_watcher;

static void stdin_cb (EV_P_ ev_io *w, int revents)
{
    puts ("stdin ready");

    ev_io_stop (EV_A_ w);

    ev_break (EV_A_ EVBREAK_ALL);
}

static void timeout_cb(EV_P_ ev_timer *w, int revents)
{
    puts("timeout");

    ev_break (EV_A_ EVBREAK_ONE);
}

int main(void)
{
    struct ev_loop *loop = EV_DEFAULT;
    ev_io_init(&stdin_watcher, stdin_cb, , EV_READ);
    ev_io_start(loop, &stdin_watcher);

    ev_timer_init(&timeout_watcher, timeout_cb, .);
    ev_timer_start(loop, &timeout_watcher);

    ev_run(loop, );

    ;
}

############注意编译命令里,除了指定输出文件,还要指定依赖的库哟

gcc -lev -o test test.c

pyev的PYTHON版:

import signal
import pyev

def sig_cb(watcher, revents):
    print("got SIGINT")
    loop = watcher.loop
    # optional - stop all watchers
    if loop.data:
        print("stopping watchers: {0}".format(loop.data))
        while loop.data:
            loop.data.pop().stop()
    # unloop all nested loop
    print("stopping the loop: {0}".format(loop))
    loop.stop(pyev.EVBREAK_ALL)

def timer_cb(watcher, revents):
    watcher.data += 1
    print("timer.data: {0}".format(watcher.data))
    print("timer.loop.iteration: {0}".format(watcher.loop.iteration))
    print("timer.loop.now(): {0}".format(watcher.loop.now()))

if __name__ == "__main__":
    loop = pyev.default_loop()
    # initialise and start a repeating timer
    timer = loop.timer(0, 2, timer_cb, 0)
    timer.start()
    # initialise and start a Signal watcher
    sig = loop.signal(signal.SIGINT, sig_cb)
    sig.start()
    loop.data = [timer, sig] # optional
    # now wait for events to arrive
    loop.start()

输出:

对比网上的EPOLL的IO复用监听事件的流程图: