萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python poll 實現高效異步 I/O 多路復用詳解

poll 機制優勢

poll() 相比 select() 移除了文件描述符數量限制,採用鏈表存儲監控對象,更適合大量連接場景。Python select.poll 對象提供面向對象接口,操作更直觀。

核心 API 詳解

1. 創建 poll 對象

import select
poller = select.poll()

2. 註冊文件描述符

poller.register(fd, eventmask)
  • fd:整數文件描述符或擁有 fileno() 的對象
  • eventmask:位掩碼組合,常用常量:
    • select.POLLIN — 可讀(普通數據)
    • select.POLLPRI — 可讀(緊急/帶外數據)
    • select.POLLOUT — 可寫
    • select.POLLERR — 錯誤狀態
    • select.POLLHUP — 掛起/連接斷開
    • select.POLLNVAL — 無效請求(未打開的 fd)

3. 輪詢就緒事件

events = poller.poll(timeout)  # timeout 毫秒,-1 為無限阻塞
# 返回 [(fd, event_mask), ...]

4. 註銷文件描述符

poller.unregister(fd)

實戰:基於 poll 的多文件複製

#!/usr/bin/env python
import select

BLKSIZE = 8192
READ_EVENTS = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR

def readwrite(from_fd, to_fd):
    data = from_fd.read(BLKSIZE)
    if data:
        to_fd.write(data)
        to_fd.flush()
    return len(data)

def copy_with_poll(fd_pairs):
    total_bytes = 0
    fd_map = {src.fileno(): (src, dst) for src, dst in fd_pairs}
    
    poller = select.poll()
    for src, _ in fd_pairs:
        poller.register(src, READ_EVENTS)
    
    while True:
        ready = poller.poll(1000)  # 1秒超時
        if not ready:
            continue
            
        for fd, event in ready:
            src, dst = fd_map[fd]
            
            if event & (select.POLLIN | select.POLLPRI):
                bytes_read = readwrite(src, dst)
                total_bytes += bytes_read
                if bytes_read <= 0:
                    poller.unregister(fd)
                    src.close()
                    dst.close()
                    
            elif event & (select.POLLERR | select.POLLHUP):
                poller.unregister(fd)
                src.close()
                dst.close()
        
        # 檢查是否所有源文件已關閉
        if not fd_map:
            break
            
    return total_bytes

def main():
    fd_pairs = [
        (open("/etc/fstab", "r"), open("/tmp/fstab.poll", "w")),
        (open("/etc/passwd", "r"), open("/tmp/passwd.poll", "w"))
    ]
    
    try:
        total = copy_with_poll(fd_pairs)
        print(f"Bytes copied: {total}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

關鍵實現細節

  1. fd 映射字典:用 fileno() 作為鍵快速查找文件對象對
  2. 事件掩碼檢測:使用位運算 event & MASK 判斷具體事件類型
  3. 錯誤處理:捕獲 POLLERR/POLLHUP 及時清理資源
  4. 超時輪詢:避免無限阻塞,定期檢查退出條件

適用場景對比

  • select:跨平台、連接數<1000、代碼簡單
  • poll:Unix/Linux、連接數較大、無 epoll 環境
  • epoll/asyncio:高併發 Linux 服務器、生產環境首選

掌握 poll 能夠在無 epoll 環境下構建高性能網絡服務,是理解異步 I/O 演進的關鍵一環。

copyright © 萬盛學電腦網 all rights reserved