簡體   English   中英

Python 3 parallel.futures套接字服務器可與ThreadPoolExecutor一起使用,但不能與ProcessPoolExecutor一起使用

[英]Python 3 concurrent.futures socket server works with ThreadPoolExecutor but not ProcessPoolExecutor

我正在嘗試使用新的current.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()

確定運行“ executor.submit(...)”后,不是由“ conn.close()”引起的嗎? 我只是刪除了這一行,並嘗試使用mac10.12.6和python 3.6.3,它運行良好。

好的Donkopotamus電話,您應該已經將其發布為答案。

我將處理程序包裝在一個try塊中,當它嘗試調用conn.recv()時,出現了異常:[Errno 10038]嘗試對不是套接字的對象進行了操作。 由於工作進程嚴重死亡,因此陷入僵局。 在適當位置使用try塊捕獲錯誤的情況下,我可以根據需要繼續進行盡可能多的連接,而不會出現任何死鎖。

如果我更改代碼以使用ThreadPoolExecutor,則不會收到此錯誤。 我嘗試了幾種選擇,但似乎沒有辦法將套接字正確傳遞給ProcessPoolExecutor中的工作進程。 我在互聯網上找到了對此的其他引用,但他們說可以在某些平台上完成,但不能在其他平台上完成。 我已經在Windows,Linux和MacOS X上進行過嘗試,但在其中任何一個上均無法使用。 這似乎是一個重大限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM