在Medium上看到一个非常棒的用来描述各种IO模型的伪代码,这些例子很好地展示了阻塞非阻塞、同步和异步的特点。
常见的I/O 类型
| Blocking | Non-blocking | Asynchronous | ||
|---|---|---|---|---|
| API | write, read | write, read + poll / select | aio_write, aio_read |
以读操作为例,不同的IO模型。对象和函数都是抽象的:
Following examples shows concepts of three I/O approaches on the reading operation. Objects and functions are abstract.
1. 阻塞,同步 Blocking, synchronous:
device = IO.open()
data = device.read() # thread will be blocked until there is data in the device
print(data)
2. 非阻塞,同步 Non-blocking, synchronous:
device = IO.open()
ready = False
while not ready:
print("There is no data to read!")
ready = IO.poll(device, IO.INPUT, 5) # returns control if 5 seconds have elapsed or there is data to read (INPUT)
data = device.read()
print(data)
3. 非阻塞,异步 Non-blocking, asynchronous:
ios = IO.IOService()
device = IO.open(ios)
def inputHandler(data, err):
"Input data handler"
if not err:
print(data)
device.readSome(inputHandler)
ios.loop() # wait till all operations have been completed and call all appropriate handlers
4. Reactor 模式 Reactor Pattern
device = IO.open()
reactor = IO.Reactor()
def inputHandler(data):
"Input data handler"
print(data)
reactor.stop()
reactor.addHandler(inputHandler, device, IO.INPUT)
reactor.run() # run reactor, which handles events and calls appropriate handlers
这些几个伪代码例子,非常好地帮助理解不同的IO模型。
为啥会有这些不同的IO模型呢?我个人的理解是,因为IO是一个比较重的耗时操作,为了最大化利用CPU资源,才有这些不同模型。其本质是在极限利用CPU,增加吞吐量和缩减响应时间。
(完)