1

我看到下面的示例代码来自一个关于如何将 libuv 与 libcurl 一起使用的示例

主要功能如下所示:

int main(int argc, char **argv) {
    loop = uv_default_loop();

    if (argc <= 1)
        return 0;

    if (curl_global_init(CURL_GLOBAL_ALL)) {
        fprintf(stderr, "Could not init cURL\n");
        return 1;
    }

    uv_timer_init(loop, &timeout);

    curl_handle = curl_multi_init();
    curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket);
    curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout);

    while (argc-- > 1) {
        add_download(argv[argc], argc);
    }

    uv_run(loop, UV_RUN_DEFAULT);
    curl_multi_cleanup(curl_handle);
    return 0;
}

我对如何进行事件循环感到困惑。因为它看起来像当我们执行这一行

uv_run(loop, UV_RUN_DEFAULT);

循环中根本没有待处理的事件,所以理论上循环不应该立即退出吗?

回调 handle_socket 应该没有任何更改才能运行。curl_perform()在 curl 套接字回调的回调中设置的没有机会运行。

我的理解有什么问题吗?

4

3 回答 3

0

uv_timer_init(loop, &timeout)不是挂起的套接字,所以它不会阻塞 uv 循环,因为它不活动(您可以检查 uv_handle_active)但curl_multi_add_handle调用超时回调函数(start_timeout)并且该函数启动timeout计时器和 uv_run 调用on_timeout回调。您可以测试它只是curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout);add_download循环之后移动并且它停止工作。

于 2014-12-22T07:25:28.770 回答
0

从文档中uv_run

/*
* This function runs the event loop. It will act differently depending on the
* specified mode:
* - UV_RUN_DEFAULT: Runs the event loop until the reference count drops to
* zero. Always returns zero.
* - UV_RUN_ONCE: Poll for new events once. Note that this function blocks if
* there are no pending events. Returns zero when done (no active handles
* or requests left), or non-zero if more events are expected (meaning you
* should run the event loop again sometime in the future).
* - UV_RUN_NOWAIT: Poll for new events once but don't block if there are no
* pending events. Returns zero when done (no active handles
* or requests left), or non-zero if more events are expected (meaning you
* should run the event loop again sometime in the future).
*/

在您的情况下,您使用 调用uv_runUV_RUN_DEFAULT并且您的引用计数永远不会变为零。这意味着循环实际上会阻塞,直到您销毁它的所有句柄和引用。但是,如果您使用 运行循环UV_RUN_NOWAIT,则该函数立即返回。

于 2014-06-25T19:49:21.650 回答
-1

注册一个异步观察者。用于uv_async_init永久强制循环。然后在异步回调中发布并处理所有新请求。

于 2015-12-10T06:56:55.007 回答