考慮下面的類:我可以認爲我的線程在threading.active_count()返回1時完成嗎?
from abc import ABCMeta, abstractmethod
from time import sleep
import threading
from threading import active_count, Thread
class ScraperPool(metaclass=ABCMeta):
Queue = []
ResultList = []
def __init__(self, Queue, MaxNumWorkers=0, ItemsPerWorker=50):
# Initialize attributes
self.MaxNumWorkers = MaxNumWorkers
self.ItemsPerWorker = ItemsPerWorker
self.Queue = Queue # For testing purposes.
def initWorkerPool(self, PrintIDs=True):
for w in range(self.NumWorkers()):
Thread(target=self.worker, args=(w + 1, PrintIDs,)).start()
sleep(1) # Explicitly wait one second for this worker to start.
def run(self):
self.initWorkerPool()
# Wait until all workers (i.e. threads) are done.
while active_count() > 1:
print("Active threads: " + str(active_count()))
sleep(5)
self.HandleResults()
def worker(self, id, printID):
if printID:
print("Starting worker " + str(id) + ".")
while (len(self.Queue) > 0):
self.scraperMethod()
if printID:
print("Worker " + str(id) + " is quiting.")
# Todo Kill is this Thread.
return
def NumWorkers(self):
return 1 # Simplified for testing purposes.
@abstractmethod
def scraperMethod(self):
pass
class TestScraper(ScraperPool):
def scraperMethod(self):
# print("I am scraping.")
# print("Scraping. Threads#: " + str(active_count()))
temp_item = self.Queue[-1]
self.Queue.pop()
self.ResultList.append(temp_item)
def HandleResults(self):
print(self.ResultList)
ScraperPool.register(TestScraper)
scraper = TestScraper(Queue=["Jaap", "Piet"])
scraper.run()
print(threading.active_count())
# print(scraper.ResultList)
當所有線程都做了,還有一個活動線程仍然是 - threading.active_count()
最後一行讓我這個數字。
活動線程爲<_MainThread(MainThread, started 12960)>
- 如threading.enumerate()
所印。
我可以假設我的所有線程都是在active_count() == 1
時完成的嗎? 或者可以,例如,導入模塊啓動額外的線程,以便我的線程實際上完成時active_count() > 1
- 也是在運行方法中使用的循環的條件。
'class TestScraper():'line is absence? – cat
爲了保持簡單,我只發佈了一部分代碼。我現在添加了一個pastebin鏈接到完整的腳本。 – user2693053
您發佈的代碼需要Minimal,Complete和Verifiable([mcve]),並且這似乎錯過了導入和定義 – cat