我们知道, Go语言为并发编程提供了简洁的编程方式, 你可以以"同步"的编程风格来并发执行代码, 比如使用go
关键字新开一个goroutine。 对于网络编程,Go标准库和运行时内部采用 epoll/kqueue/IoCompletionPort
来实现基于 event-loop
的网络异步处理,但是通过netpoll
的方式对外提供同步的访问。具体代码可以参考 runtime/netpoll、net和internal/poll。
Package poll supports non-blocking I/O on file descriptors with polling.
This supports I/O operations that block only a goroutine, not a thread.
This is used by the net and os packages.
It uses a poller built into the runtime, with support from the
runtime scheduler.
当然,我们平常不会设计到这些封装的细节,正常使用net
包就很方便的开发网络程序了, 但是,如果我们想自己实现基于epoll
的 event-loop
网络程序呢?