0

私は、この文が実際に何を意味するのかを誤解している可能性がある問題に直面しています。または、それを行う方法の適切なドキュメントが見つかりません。問題は、event_dispatch() で実行した後、イベント ループにイベントを追加できるはずだと思うのですが、機能しないことです。コードは次のとおりです。

#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>

#include <stdio.h>

static int n_calls = 0;
static int n_calls2 = 0;

void cb_func(evutil_socket_t fd, short what, void *arg)
{
    struct event *me = arg;

    printf("cb_func called %d times so far.\n", ++n_calls);

    if (n_calls > 100)
       event_del(me);
}

void cb_func2(evutil_socket_t fd, short what, void *arg)
{
    struct event *me = arg;

    printf("cb_func2 called %d times so far.\n", ++n_calls2);

    if (n_calls2 > 100)
       event_del(me);
}

int main(int argc, char const *argv[])
{
    struct event_base *base;
    enum event_method_feature f;

    base = event_base_new();
    if (!base) {
        puts("Couldn't get an event_base!");
    } else {
        printf("Using Libevent with backend method %s.",
            event_base_get_method(base));
        f = event_base_get_features(base);
        if ((f & EV_FEATURE_ET))
            printf("  Edge-triggered events are supported.");
        if ((f & EV_FEATURE_O1))
            printf("  O(1) event notification is supported.");
        if ((f & EV_FEATURE_FDS))
            printf("  All FD types are supported.");
        puts("");
    }

    struct timeval one_sec = { 1, 0 };
    struct timeval two_sec = { 2, 0 };
    struct event *ev;
    /* We're going to set up a repeating timer to get called called 100 times. */
    ev = event_new(base, -1, EV_PERSIST, cb_func, NULL);
    event_add(ev, &one_sec);

    event_base_dispatch(base);

    // This event (two_sec) is never fired if I add it after calling event_base_dispatch. 
    // If I add it before calling event_base_dispatch it works as the other event (one_sec) also does.
    ev = event_new(base, -1, EV_PERSIST, cb_func2, NULL);
    event_add(ev, &two_sec);

    return 0;
}
4

1 に答える 1

1

今見ました...理由はわかりませんが、イベントループが別のスレッドなどで実行を開始したと考えていました。私がやろうとしていたことが意味をなさないことが今わかりました。コールバック内、つまりループの実行中にイベントを追加できます。イベントループを開始すると、それは決して返されないため、その後のすべてが呼び出されることはありません (イベントループを停止しない限り)

于 2015-03-19T21:26:13.037 に答える