实践[C语言] libuv[2] libuv uv_loop_t事件循环

163 阅读2分钟

libuv针对不同类型的操作提供了不同的handler,我们可以根据需要进行自定义处理。

uv_loop_t       事件循环
uv_handle_t     抽象handler基类
uv_req_t        抽象请求类型
uv_timer_t      定时器handler
uv_prepare_t    准备阶段handler
uv_check_t      检查阶段handler
uv_idle_t       空闲阶段handler
uv_async_t      异步操作handler
uv_poll_t       轮询操作handler
uv_signal_t     信号量监听handler
uv_process_t    进程管理handler
uv_stream_t     流handler
uv_tcp_t        TCP网络通讯handler
uv_pipe_t       管道handler
uv_tty_t        终端handler
uv_udp_t        UDP通讯handler
uv_fs_event_t   文件事件handler
uv_fs_poll_t    文件系统轮询handler

uv_loop_t事件循环

事件循环是libuv功能的核心部分。它负责轮询i/o和调度基于不同的事件源运行的回调。 它主要提供了一个结构体,一个枚举和若干方法

uv_loop_t结构体描述

struct uv_loop_s {
  /* 用户数据指针 */
  void* data;
  /* 循环引用计数器 */
  unsigned int active_handles;
  /* 循环队列 */
  struct uv__queue handle_queue;
  union {
    void* unused;
    unsigned int count;
  } active_reqs;
  /* 内部存储扩展点 */
  void* internal_fields;
  /* 信号循环停止标志位 */
  unsigned int stop_flag;
  UV_LOOP_PRIVATE_FIELDS
};
UV_LOOP_PRIVATE_FILEDS

uv_loop的专用属性,使用预编译宏声明

{
  unsigned long flags;
  int backend_fd;
  struct uv__queue pending_queue;
  struct uv__queue watcher_queue;
  uv__io_t** watchers;
  unsigned int nwatchers;
  unsigned int nfds;
  struct uv__queue wq;
  uv_mutex_t wq_mutex;
  uv_async_t wq_async;
  uv_rwlock_t cloexec_lock;
  uv_handle_t* closing_handles;
  struct uv__queue process_handles;
  struct uv__queue prepare_handles;
  struct uv__queue check_handles;
  struct uv__queue idle_handles;
  struct uv__queue async_handles;
  void (*async_unused)(void);
  uv__io_t async_io_watcher;
  int async_wfd;
  struct {
    void* min;
    unsigned int nelts;
  } timer_heap;
  uint64_t timer_counter;
  uint64_t time;
  int signal_pipefd[2];
  uv__io_t signal_io_watcher;           // 信号量监听
  uv_signal_t child_watcher;            // 子元素信号量监听
  int emfile_fd;
  UV_PLATFORM_LOOP_FIELDS;              // linux平台下默认是空
}

运行方式

UV_RUN_DEFAULT
UV_RUN_ONCE
UV_RUN_NOWAIT

方法

uv_loop_init       初始化传入的uv_loop_t结构体
uv_loop_configure  另外设置loop的配置
uv_loop_close      释放循环资源
uv_default_loop    返回默认的loop
uv_run             运行已创建的loop
uv_loop_active     检测loop中是否有活跃的事件回调
uv_stop            停止传入的loop
uv_loop_size       返回uv_loop_t的结构体大小
uv_backend_fd      可以在一个线程中轮询并在另一个线程中运行的事件循环回调
uv_backend_timeout 获取轮询超时,返回值以毫秒为单位
uv_now             返回当前时间戳,事件循环的时间戳缓存在事件循环开始的地方。
uv_update_time     更新事件循环的uv_now的时间戳
uv_walk            遍历句柄列表,并使用给定的参数执行
uv_loop_fork       重新初始化子进程中所需的任何内核状态fork系统调用。
uv_loop_get_data   返回loop数据
uv_loop_set_data   设置loop数据