如何解决Python线程无法运行
我正在使用线程在Python上制作服务器程序,您可以在其中使用socket
模块进行注册,登录等。我还使用了threading
模块来处理多个用户,但是当我运行程序时,它抛出了错误。
这是我的代码:
import threading
import socket
import json
host = socket.gethostbyname(socket.gethostname())
port = 8765
print("IP:",host)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
with open("users.json") as file:
users = json.load(file)["users"]
cnts = []
def client():
c,a = s.accept()
acc = None
while 1:
req = c.recv(1)
if req == b"b":
break
elif req == b"r":
name = c.recv(c.recv(1)[0])
if len(name) < 3:
c.send("\x01")
elif len(name) > 20:
c.send("\x02")
elif name in users:
c.send("\x03")
else:
pwd = c.recv(c.recv(1)[0])
if len(pwd) < 4:
c.send("\x01")
elif len(pwd) > 12:
c.send("\x02")
else:
c.send("\x00")
users[name] = pwd
acc = name
elif req == b"s":
name = c.recv(c.recv(1)[0])
if name in users:
pwd = c.recv(c.recv(1)[0])
if users[name] == pwd:
acc = name
c.send("\x00")
else:
c.send("\x02")
else:
c.send("\x01")
c.close()
s.listen(1)
quit = 0
while not quit:
thread = threading.Thread(target=client)
thread.start()
cnts.append(thread)
程序输出:
> py server.py
IP: 192.168.0.106
Traceback (most recent call last):
File "server.py",line 72,in <module>
thread.start()
File "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\lib\threading.py",line 852,in start
_start_new_thread(self._bootstrap,())
RuntimeError: can't start new thread
我是python线程的新手,所以我不明白自己做错了什么。
编辑:已修复。感谢您的回答。
新代码:
import threading
import socket
import json
host = socket.gethostbyname(socket.gethostname())
port = 8765
print("IP:",port))
with open("users.json") as file:
users = json.load(file)["users"]
cnts = []
waiting = 1
def client():
global waiting
c,a = s.accept()
waiting = 0
acc = None
while 1:
req = c.recv(1)
if req == b"b":
break
elif req == b"r":
name = c.recv(c.recv(1)[0])
if len(name) < 3:
c.send("\x01")
elif len(name) > 20:
c.send("\x02")
elif name in users:
c.send("\x03")
else:
pwd = c.recv(c.recv(1)[0])
if len(pwd) < 4:
c.send("\x01")
elif len(pwd) > 12:
c.send("\x02")
else:
c.send("\x00")
users[name] = pwd
acc = name
elif req == b"s":
name = c.recv(c.recv(1)[0])
if name in users:
pwd = c.recv(c.recv(1)[0])
if users[name] == pwd:
acc = name
c.send("\x00")
else:
c.send("\x02")
else:
c.send("\x01")
c.close()
s.listen(1)
quit = 0
counter = 0
while not quit:
thread = threading.Thread(target=client)
thread.start()
cnts.append(thread)
counter += 1
while waiting:
pass
waiting = 1
解决方法
while not quit:
主体没有任何阻碍执行的内容,例如input
,socket.recv
或time.sleep
。这意味着,此循环非常快速地执行每个迭代,并且每次迭代都会创建一个新线程。尝试用while not quit:
代替for _ in range(3)
,以仅产生3个线程。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。