【问题标题】:Is it normal to call uv_run several times?多次调用uv_run正常吗?
【发布时间】:2016-10-19 12:02:50
【问题描述】:

我是uvlib 的新手。如果想避免阻塞内部函数,两次调用uv_run 是否正常?如果没有,那么除了线程之外还有哪些可用的工具?这里我只是打开和关闭文件。

#include <uv.h>
#include <stdio.h>
#include <fcntl.h>
#include <conio.h>
#ifdef _WIN32
    #include <conio.h>
    #include <Windows.h>
    #define Sleep(x) Sleep(x)
#else
    #include <unistd.h>
    #define Sleep(x) sleep(x)
#endif

uv_loop_t* loop;

uv_fs_t open_req;
uv_fs_t close_req;

void open_cb(uv_fs_t*);
void close_cb(uv_fs_t*);

const char *filename = "C:/c/somedata.txt";

int main(int argc, char **argv) {
    int r;

    loop = uv_loop_new();

    r = uv_fs_open(loop, &open_req, filename, O_RDONLY, S_IREAD, open_cb);
    if (r < 0) {
        printf("Error at opening file: %s\n", uv_strerror(r));
    }
    printf("in main now\n");
    uv_run(loop, UV_RUN_DEFAULT);
    uv_loop_close(loop);
    return 0;
}

void open_cb(uv_fs_t* req) {
    int result = req->result;

    if (result < 0) {
        printf("Error at opening file: %s\n", uv_strerror(result));
    } else {
        printf("Successfully opened file.\n");
    }
    uv_fs_req_cleanup(req);
    uv_fs_close(loop, &close_req, result, close_cb);
    uv_run(loop, UV_RUN_DEFAULT);
    Sleep(5000);
    printf("ok now\n");
}

void close_cb(uv_fs_t* req) {
    int result = req->result;
    printf("in close_cb now\n");

    if (result < 0) {
        printf("Error at closing file: %s\n", uv_strerror(result));
    } else {
        printf("Successfully closed file.\n");
    }
}

【问题讨论】:

    标签: c asynchronous filesystems libuv


    【解决方案1】:

    抛开你的例子,libuv 提供了多次运行循环的机会。
    有关详细信息,请参阅documentation

    特别是,uv_run 函数接受 uv_run_mode 类型的参数。
    可能的值是:

    • UV_RUN_DEFAULT:它不会停止,除非您明确停止它并且直到循环中至少存在一个引用或活动资源。

    • UV_RUN_ONCE:轮询 I/O 一次并执行所有准备就绪的函数。它的缺点是如果没有挂起的回调它会阻塞。

    • UV_RUN_NOWAIT:这可能就是你要找的那个,和上一个类似,但是如果没有挂起的回调它不会阻塞。

    请注意,对于UV_RUN_ONCEUV_RUN_NOWAIT,您必须多次运行循环。
    返回值通常指示是否还有其他待处理的回调。在这种情况下,循环必须在未来迟早运行。

    最后一种模式UV_RUN_NOWAIT 可能是您要寻找的模式。
    例如,它可以用于客户端有自己的循环并且不能阻塞在libuv的循环的场景。


    多次运行循环是否正常?
    嗯,是的,但这主要取决于您的实际问题是否正确。
    从 SO 上的 100 行 sn-p 很难说。

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 2018-07-16
      • 1970-01-01
      相关资源
      最近更新 更多