我正在尝试使用新的 concurrent.futures 类创建一个简单的套接字服务器。我可以让它与 ThreadPoolExecutor 一起正常工作,但是当我使用 ProcessPoolExecutor 时它只是挂起,我不明白为什么。鉴于这种情况,我认为这可能与试图将某些不能腌制的子进程传递给子进程有关,但我不这么认为。我的代码的简化版本如下。我会很感激任何建议。
import concurrent.futures
import socket, os
HOST = ''
PORT = 9001
def request_handler(conn, addr):
pid = os.getpid()
print('PID', pid, 'handling connection from', addr)
while True:
data = conn.recv(1024)
if not data:
print('PID', pid, 'end connection')
break
print('PID', pid, 'received:', bytes.decode(data))
conn.send(data)
conn.close()
def main():
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
sock.listen(10)
print("Server listening on port", PORT)
while True:
conn, addr = sock.accept()
executor.submit(request_handler, conn, addr)
conn.close()
print("Server shutting down")
if __name__ == '__main__':
main()