本文分析并解决使用python多进程处理并发tcp请求时,客户端在macos系统上卡死的问题(在ubuntu系统上运行正常)。问题根源在于服务端在多进程环境下直接共享socket.socket对象,导致资源竞争。
原始代码直接在进程池中处理socket.socket对象,这并非线程安全操作。不同操作系统对这种资源竞争的处理方式不同,因此导致macOS系统出现卡死,而Ubuntu系统正常运行。
解决方案:避免进程间共享socket.socket对象
改进后的服务端代码通过以下步骤解决问题:
立即学习“Python免费学习笔记(深入)”;
使用文件描述符: serversocket.accept()返回的clientsocket是一个socket对象。 通过clientsocket.fileno()获取其对应的文件描述符,文件描述符是进程安全的。
进程内创建socket: 在子进程中,使用socket.fromfd()函数根据文件描述符重新创建一个socket对象,确保每个子进程拥有独立的socket对象,避免资源竞争。
关闭文件描述符: 在start_request函数中,使用os.close(clientsocket_fd)关闭进程池传入的文件描述符,防止资源泄漏。
finally语句: start_request函数使用finally语句确保无论是否发生异常,都能正确关闭socket连接,释放资源。
改进后的代码:
import os import socket import sys import time import threading from loguru import logger from concurrent.futures import ThreadPoolExecutor from concurrent.futures._base import Future import multiprocessing default_encoding: str = 'utf-8' # ... (init_serversocket function remains unchanged) ... def send_response(clientsocket: socket.socket, addr: tuple, response_body: bytes) -> int: send_len: int = clientsocket.send(response_body) clientsocket.close() return send_len def start_request(clientsocket_fd: int, addr: tuple) -> int: clientsocket = socket.fromfd(clientsocket_fd, socket.AF_INET, socket.SOCK_STREAM) os.close(clientsocket_fd) # Close the FD after duplication try: pid = os.getpid() logger.debug(f'pid: {pid}, get message from {addr}') request_body: bytes = clientsocket.recv(2048) request_text: str = request_body.decode(encoding=default_encoding) response_text: str = f'server get message: {request_text}' response_body: bytes = response_text.encode(default_encoding) send_len = send_response(clientsocket, addr, response_body) logger.debug(f'发送了响应') return send_len except Exception as error: logger.exception(error) finally: clientsocket.close() # Ensure closure even if exceptions occur def worker_process(clientsocket_fd, addr): start_request(clientsocket_fd, addr) # ... (rest of the code remains largely unchanged) ...
通过以上修改,服务端能够正确处理并发TCP请求,避免客户端卡死。关键在于正确处理多进程环境下socket对象的共享问题,避免资源竞争和死锁。
以上就是Python多进程处理并发TCP请求导致客户端卡死的原因是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号