如何打破libevent的调度循环 [英] How to break out libevent's dispatch loop

查看:590
本文介绍了如何打破libevent的调度循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个单独的线程中使用nice libevent库实现了一个小的web服务器。 Web服务器运行event_base_dispatch()以处理所有事件。我需要的是一种方法来打破这个调度循环从主线程。

I've implemented a tiny webserver in a separate thread using the nice libevent library. The webserver runs event_base_dispatch() to process all events. What I need is a way to break out this dispatch loop from the main thread.

它可以归结为以下C ++代码:

It boils down to the following C++ code:

#include <stdlib.h>
#include <signal.h>
#include <thread>
#include <evhttp.h>

struct event_base *eb;
std::thread t;

static volatile sig_atomic_t bailout = false;

void my_signal_handler(int) {
    bailout = true;
}

void onRequest(evhttp_request *req, void *) {
    struct evbuffer *OutBuf = evhttp_request_get_output_buffer(req);
    evbuffer_add_printf(OutBuf, "<html><body>Testing 1-2-3</body></html>");
    evhttp_send_reply(req, HTTP_OK, "OK", OutBuf);
}

void dispatch() {
    eb = event_base_new();
    struct evhttp *http = evhttp_new(eb);
    evhttp_set_gencb(http, &onRequest, NULL);
    evhttp_bind_socket_with_handle(http, "0.0.0.0", 5555);
    event_base_dispatch(eb);
}

int main() {

    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = my_signal_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);

    t = std::thread { &dispatch };

    while ( ! bailout ) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    event_base_loopexit(eb, NULL);

    t.join();
}

行为是,如果您运行程序,请求页面,程序通过Ctrl-C,event_base_dispatch()继续运行,直到您获取另一个网页。

The behavior is that if you run the program, request a page, abort the program by Ctrl-C, the event_base_dispatch() keeps running until you fetch another web page. Only then the loop aborts and the program terminates.

推荐答案

如果需要在运行任何更多回调之前退出事件循环,请使用event_base_break()

If you need the event loop to exit before running any more callbacks, use event_base_break()

http://www.wangafu.net/~nickm/libevent-book/Ref3_eventloop.html

这篇关于如何打破libevent的调度循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆