上篇 使用 libevent 在 timer 使用了兩個 struct event_base 在不同的 thread 執行 , 

看了 http://rxwen.blogspot.tw/2012/11/user-event-in-libevent.html 發現可以使用以下方式讓

相同的 event_base 可以在不同的 thread 執行 ::

 

原來的 code :

static int n_calls = 0;

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

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

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

void *functimer(void *arg)
{
    pthread_detach(pthread_self());

    struct event_base *base = event_base_new();
    struct timeval one_sec = { 1, 0 };
    struct event *ev;

    ev = event_new(base, -1, EV_PERSIST, cb_timerfunc, event_self_cbarg());
    event_add(ev, &one_sec);
    event_base_dispatch(base);

} //functimer

    pthread_t t1 ;
    int iCPU1 = 0 ;
    pthread_create(&t1,NULL,functimer,(void *)(long)iCPU1 );

 

新的 code :

#include <event2/thread.h>

static int n_calls = 0;
void cb_timerfunc(evutil_socket_t fd, short what, void *arg)
{
    struct event *me = (struct event *) arg;

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

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

void *functimer(void *arg)
{
    //pthread_detach(pthread_self());

    //struct event_base *base = event_base_new();
    struct event_base *base = (struct event_base*) arg ;
    struct timeval one_sec = { 1, 0 };
    struct event *ev;

    ev = event_new(base, -1, EV_PERSIST, cb_timerfunc, event_self_cbarg());
    event_add(ev, &one_sec);
    //event_base_dispatch(base);

} //functimer

    struct event_base *base = event_base_new();
    assert(base != NULL);

    evthread_use_pthreads();
    if (evthread_make_base_notifiable(base)<0) {
        printf("Couldn't make base notifiable!");
        return 1;
    }

    pthread_t t1 ;
    pthread_create(&t1,NULL,functimer,(void *)base );

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()