我想创建一个简单的套接字服务器使用新的concurrent.futures类。我可以使用ThreadPoolExecutor正常工作,但是当我使用ProcessPoolExecutor时它会挂起,我不明白为什么。考虑到这种情况,我认为这可能与尝试将某些事情传递给儿童流程不可兼得,但我并非如此。下面是我的代码的简化版本。我将不胜感激任何建议。Python 3 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中ProcessPoolExecutor会死锁,如果一个工人死亡严重(例如没有退出值0)。 – donkopotamus
良好的电话@Donkopotamus,你应该发布这个答案而不是评论。 – ThatAintWorking