简体   繁体   English

在libev事件回调函数内部调用阻止功能是否会阻止整个应用程序?

[英]Does calling a blocking function inside libev event callback function blocks whole app?

I use libev to develope my event-driven app. 我使用libev开发我的事件驱动的应用程序。 I like to query remote mysql server inside events. 我喜欢查询事件内部的远程mysql服务器。 so, Do mysql_real_connect block whole application or just my_read_cb 因此, mysql_real_connect是阻止整个应用程序还是只是my_read_cb

according to following code 根据以下代码

my_read_cb(EV_P_ ev_io *w, int revents) {

    mysql_real_connect(*mysql, "host", "user", "pass", "db", 3306, NULL, 0);
}


struct ev_loop *loop = ev_default_loop(0);
ev_io_init(io, my_read_cb, network_fd, EV_READ);
ev_io_start(loop, io);
ev_run(loop, 0);

It blocks the whole application because the callback function my_read_cb() is executed in the same (aka main) thread as ev_run() function. 它阻止了整个应用程序,因为回调函数my_read_cb()ev_run()函数在同一线程(即主线程ev_run()执行。 This is how reactor pattern works, your code should be "non-blocking" which means that you should avoid any I/O waits, sleep() calls, mutex waits etc. It is difficult to follow such a requirement with traditional blocking code from various libraries such as MySQL driver in your case. 这就是反应堆模式的工作方式,您的代码应为“非阻塞”状态,这意味着您应避免任何I / O等待, sleep()调用,互斥体等待等。使用传统的阻塞代码很难满足此类要求各种库,例如MySQL驱动程序。

There are (at least) three ways how to solve it: 有(至少)三种解决方法:

  • Accept the fact that event loop is blocked time-to-time. 接受事件循环有时会被阻塞的事实。 It may not be a such a big deal in some apps. 在某些应用中,这可能不是什么大问题。
  • Implement proactor pattern - that basically means that each handler callback is executed in a worker thread different from a main thread and for that reason, the event loop is not blocked. 实现proactor模式 -基本上意味着,每个处理程序回调都在与主线程不同的工作线程中执行,因此,事件循环不会被阻塞。 This is what Node.js provides or in C world libuv and so on. 这就是Node.js提供的或C语言世界中的libuv等。
  • Find an asynchronous/non-blocking implementation of the library compatible with your event loop. 查找与事件循环兼容的库的异步/非阻塞实现。 You need to be particularly lucky here. 您需要在这里特别幸运。 An example is eg https://c-ares.haxx.se for async DNS resolving (in contrast to POSIX system DNS blocking calls in getaddrinfo family). 例如, https//c-ares.haxx.se用于异步DNS解析(与getaddrinfo系列中的POSIX系统DNS阻止调用相反)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM