【发布时间】:2011-09-25 22:02:30
【问题描述】:
我正在尝试使用新的 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()
【问题讨论】:
-
如果它有帮助,在 Python 3.2 中,如果工作人员严重死亡(例如,没有退出值 0),ProcessPoolExecutor 会死锁。
-
好电话@Donkopotamus,您应该将其发布为答案而不是评论。
标签: python sockets python-3.x python-3.2 concurrent.futures