【发布时间】:2015-08-29 05:27:33
【问题描述】:
我收到以下错误:
----- Match 93028: ------ Patch 5.11 ------78 Threads Active
----- Match 93029: ------ Patch 5.11 ------77 Threads Active
----- Match 93030: ------ Patch 5.11 ------76 Threads Active
----- Match 93031: ------ Patch 5.11 ------71 Threads Active
----- Match 93032: ------ Patch 5.11 ------55 Threads Active
----- Match 93033: ------ Patch 5.11 ------56 Threads Active
----- Match 93034: ------ Patch 5.11 ------57 Threads Active
----- Match 93035: ------ Patch 5.11 ------58 Threads Active
----- Match 93036: ------ Patch 5.11 ------59 Threads Active
Traceback (most recent call last):
File "pulldata.py", line 91, in <module>
getPatchData('5.11', '511')
File "pulldata.py", line 64, in getPatchData
matchThread.start()
File "/usr/lib/python3.4/threading.py", line 850, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread
这通常是由于打开的线程过多造成的,但正如您所见,我还打印了活动线程的数量。有
slot = threading.BoundedSemaphore(value=1000)
def getMatchData(index,match,patch):
global requestsSent
global logfile
print("----- Match {0}: ------ Patch {1} ------{2} Threads Active".format(index,patch,threading.active_count()))
logfile.write("Parsing Match {0} for patch {1}:\n".format(index,patch))
#match is a class. get is a function that sends a request to the server and returns a request object from where I get the json response.
data = match.get().json()
#processdata
slot.release()
def getPatchData(patch, name):
global logfile
threads = []
matches = getAllMatches(patch)
for index, match in enumerate(matches):
slot.acquire()
matchThread = threading.Thread(target=getMatchData, args=(index,match,patch))
threads.append(matchThread)
matchThread.start()
for t in threads:
if not t.isAlive():
threads.remove(t)
for t in threads:
t.join()
插槽信号量应该限制活动线程的数量,但我认为我从来没有达到 1000 个线程。在我假设这个错误是由于我的线程数组指向的线程引起的,所以我添加了代码以在它们不再处于活动状态时将它们从数组中删除。
我不明白为什么只有 59 个活动线程时无法启动新线程。
另外,有没有更好的方法来实现我想要做的事情?每个线程向 API 发送一个请求。我尝试在没有并发的情况下执行此操作,但我什至没有接近我的速率限制。
【问题讨论】:
-
尝试:排队 @hauzron docs.python.org/2/library/queue.html
-
感谢您的帮助,但现在我有内存泄漏:stackoverflow.com/questions/32286299/…
标签: python multithreading