在 PYTHON 中使用 SOCKET 的线程中不能引发异常

问题描述 投票:0回答:0

我尝试从 Python 线程引发异常。如果线程内部有一个套接字接收,我就不会这样做。

这里是客户端的代码:

from concurrent import futures
import traceback, time, socket

def cpu_process(thread_idx: int):
    socket_file = 'socket0'

    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as gpu_client:
        gpu_client.connect(socket_file)
        data_len_bin = int(123).to_bytes(4, 'big')
        gpu_client.sendall(data_len_bin)
        response_bytes = gpu_client.recv(1024) # If you comment this line, everything will run as expected.

    time.sleep(4)
    return thread_idx

def moderate():
    future_results = []
    try:
        with futures.ThreadPoolExecutor(max_workers=4) as executor:
            for thread_idx in range(8):
                future_results.append(executor.submit(cpu_process, thread_idx))

            for future in future_results:
                try:
                    response = future.result(timeout=3)
                except Exception as e:
                    print(f"Inner exception traceback:\n {traceback.format_exc()}")
                    raise Exception('CPU Process Exception').with_traceback(e.__traceback__)
    
    except Exception as e:
        print("Exterior exception")
        return 'Fail'
    return 'Success'

if __name__ == "__main__":
    moderate() # "Exterior exception"

我有一个监听端口但没有返回任何内容的服务器。如果我评论上面代码中的

response_bytes = gpu_client.recv(1024)
行,一切顺利,最后打印
Exterior exception
。同时,当前代码从不打印
Exterior exception
.

我的问题是:

  1. 为什么即使我提出 TimeoutError
    gpu_client.recv(1024)
    也会阻止线程?
  2. 克服障碍的最佳方法是什么?

非常感谢你。

multithreading sockets exception python-multithreading python-sockets
© www.soinside.com 2019 - 2024. All rights reserved.