首页 > 解决方案 > 运行时错误无法启动新线程

问题描述

我正在尝试检查一个端口上是否有可用的数据。如果这是可用的,则应将消息“是”发送到另一个端口,如果没有数据,则应发送“否”消息。客户端正在连接到“是”或“否”即将到来的那个端口。我运行脚本,一切看起来都很好。但是一小时后我得到了错误:运行时错误无法启动新线程。线程 11 中的异常:Traceback< 最近一次调用:文件 threading.py 引导带内部的第 914 行。

我是 python 新手,我真的不明白发生了什么。我的代码包含许多线程,因为我正在检查来自 10 个端口的数据并向其他 10 个端口发送“是”或“否”消息。这是我的 1 端口代码的一部分:

    import time
import socket
import threading
from threading import Thread
import select

#-----------------------------------Server --------------------------
s = socket.socket(socket.AF_INET) #Socket
h = '127.0.0.1' #Host where data coming from
p = 14201 #Port
halarm = "127.0.0.1" # A port will be opened to send availabilty status
palarm = 14202 # Port
def Server ():
    while True:
        try:
            time.sleep(0.1)
            s.connect((h, p))
        except socket.error:
            pass

#-----------------------------------Server/Client -------------------------------
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((halarm, palarm)) # Bind to the Port where
sock.listen(1)        
def func(conn): # Server-Client Function 
    while True:
        try:
            global s
            Timeout = select.select([s], [], [], 5)# Timeout in seconds
            connected = True
            while True:

                try:
                    if Timeout[0]:
                        conn.send(bytes("yes", "utf-8"))
                        time.sleep(3)
                    else:
                        conn.send(bytes("no", "utf-8"))
                        time.sleep(3)
                    newConnection= False
                    while not newConnection:
                        try:
                            s = socket.socket(socket.AF_INET)
                            s.connect((h, p))
                            Timeout = select.select([s], [], [], 5)# Timeout in seconds
                            newConnection= True
                        except socket.error:
                            conn.send(bytes("Port is closed", "utf-8"))                            
                            time.sleep(3)
                            pass
                except socket.error:
                    pass
        except:
            pass
def connThread():
    while True:
        conn, addr = sock.accept()
        time.sleep(0.1)
        Thread(target = func, args=(conn,)).start()

if __name__ == '__main__':
    Thread(target = Server).start()
    Thread(target = connThread).start()

我怎么解决这个问题 ?我感谢您的所有帮助。

标签: pythonmultithreadingpython-3.xtcppython-multithreading

解决方案


推荐阅读