python - Python 线程/请求问题
问题描述
我在 Python 中有一个多线程代码(每秒触发几个线程并在之后关闭它们),它曾经工作正常。最近,我添加了一个新函数(线程),用于通过获取请求(10 秒超时)侦听某些表的服务器(因为它们是从服务器流出的)。
问题是代码可以正常工作大约 1-2 小时,然后我得到 python 线程错误"error: can't start new thread",只有大约 20 个活动线程。
我尝试拥有一个单例线程池并使用它,但它根本没有帮助。
附带说明一下,从函数中删除此 get 请求可以解决问题,并且代码可以完美运行。
请告诉我你的意见,谢谢。
def getStreamData(self):
if (self.liveTablesTimer == None):
self.startLiveTablesTimer()
print("LiveTables timer started")
self.voidTableCount += 1 # counting for connection refresh
def separateThread():
try:
#return 0
self.streamInConnection = requests.get(self.liveTablesUrl, stream=True, verify=False, timeout=10)
#print("Live tables request sent as:", self.liveTablesUrl)
if self.streamInConnection.encoding is None:
self.streamInConnection.encoding = 'utf-8'
for line in self.streamInConnection.iter_lines(decode_unicode=True):
if line and self.userName != None:
#print("Raw stream received", line)
self.streamData.emit(line)
except:
print("getLiveTables stream link timeout")
self.streamInConnection.close()
if (self.voidTableCount>6*5): #5 min
try:
self.voidTableCount=0
pass
except:
pass
finally:
return 0
try:
print("Starting thread for receiving liveTables data")
#self.consCheck.threadExecutor.submit(separateThread)
thread = threading.Thread(target=separateThread, args=[], daemon = True)
thread.start()
except Exception as err:
print("liveTables stream error:", err)
解决方案
奇怪的是,我从请求中删除了“验证”参数,它解决了这个问题。
requests.get(self.liveTablesUrl, stream=True, timeout=10)