上一篇文章解析了fd是怎么与io模型关联。其中最主要的角色扮演者:hio_t
1. hio_t
与hloop
的关系
fd的值即hio_t所在loop ios变量中所在的index值。
hio_t = ios[fd]
struct hloop_s {
...// ios: with fd as array.index//io_array保存了和hloop关联的所有hio_t,并且fd的值即hio_t在io_array中的下标//hio_t = ios[fd]struct io_array ios;
}
2.hio_t
与hloop
绑定
通过
hio_get
与hloop
进行绑定
hio_t* hio_get(hloop_t* loop, int fd) {//如果fd的值大于ios的最大值则重新分配大小if (fd >= loop->ios.maxsize) {int newsize = ceil2e(fd);io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd);}//如果当前hio_t不存在则重新分配并且初始化hio_t* io = loop->ios.ptr[fd];if (io == NULL) {HV_ALLOC_SIZEOF(io);hio_init(io);io->event_type = HEVENT_TYPE_IO;io->loop = loop;io->fd = fd;loop->ios.ptr[fd] = io;}//标记hio_t状态已经ready,hio_ready即初始化数据if (!io->ready) {hio_ready(io);}return io;
}hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) {hio_t* io = hio_get(loop, fd);
...
}hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) {hio_t* io = hio_get(loop, fd);
...
}
3.hio_t
与io模型
绑定与解除
hio_add与io模型绑定
iowatcher_add_event
hio_del与io模型解除绑定iowatcher_del_event
疑问解答
- 同一个loop的所有hio_t的readbuf均指向loop本身的readbuf,不会发生数据覆盖么?
答:不会,因为loop工作的前提是单线程模式,所以不存在多个io同时读的问题。