各プロセスが別のスレッドでタイムアウトを使用して結合される構成を試してください。そのため、メイン プログラムがスタックすることはなく、プロセスがスタックすると、タイムアウトにより強制終了されます。この手法は、スレッド化モジュールとマルチプロセッシング モジュールを組み合わせたものです。
これは、メモリ内のスレッドの最小 x 数を維持する私の方法です。スレッド化モジュールとマルチプロセッシング モジュールの組み合わせです。尊敬されている仲間のメンバーが上で説明したような他のテクニックには珍しいかもしれませんが、かなりの価値があるかもしれません. 説明のために、一度に最低 5 つの Web サイトをクロールするシナリオを取り上げます。
だからここにあります:-
#importing dependencies.
from multiprocessing import Process
from threading import Thread
import threading
# Crawler function
def crawler(domain):
# define crawler technique here.
output.write(scrapeddata + "\n")
pass
次はthreadController関数です。この関数は、メイン メモリへのスレッドの流れを制御します。threadNum の「最小」制限を維持するためにスレッドをアクティブ化し続けます。5. また、すべてのアクティブなスレッド (acitveCount) が終了するまで終了しません。
最小の threadNum(5) startProcess 関数スレッドを維持します (これらのスレッドは、60 秒のタイムアウトでプロセスに参加しながら、最終的に processList からプロセスを開始します)。threadController を開始すると、上記の制限 5 に含まれない 2 つのスレッドが存在します。Main スレッドと threadController スレッド自体。それが threading.activeCount() != 2 が使用された理由です。
def threadController():
print "Thread count before child thread starts is:-", threading.activeCount(), len(processList)
# staring first thread. This will make the activeCount=3
Thread(target = startProcess).start()
# loop while thread List is not empty OR active threads have not finished up.
while len(processList) != 0 or threading.activeCount() != 2:
if (threading.activeCount() < (threadNum + 2) and # if count of active threads are less than the Minimum AND
len(processList) != 0): # processList is not empty
Thread(target = startProcess).start() # This line would start startThreads function as a seperate thread **
startProcess 関数は、別のスレッドとして、プロセスリストからプロセスを開始します。この関数 (**別のスレッドとして開始) の目的は、プロセスの親スレッドになることです。したがって、60 秒のタイムアウトでそれらに参加すると、startProcess スレッドが先に進むのを停止しますが、threadController の実行は停止しません。このように、threadController は必要に応じて機能します。
def startProcess():
pr = processList.pop(0)
pr.start()
pr.join(60.00) # joining the thread with time out of 60 seconds as a float.
if __name__ == '__main__':
# a file holding a list of domains
domains = open("Domains.txt", "r").read().split("\n")
output = open("test.txt", "a")
processList = [] # thread list
threadNum = 5 # number of thread initiated processes to be run at one time
# making process List
for r in range(0, len(domains), 1):
domain = domains[r].strip()
p = Process(target = crawler, args = (domain,))
processList.append(p) # making a list of performer threads.
# starting the threadController as a seperate thread.
mt = Thread(target = threadController)
mt.start()
mt.join() # won't let go next until threadController thread finishes.
output.close()
print "Done"
メモリ内のスレッドの最小数を維持することに加えて、私の目的は、メモリ内のスタック スレッドやプロセスを回避できるものを用意することでもありました。タイムアウト機能を使用してこれを行いました。入力ミスについてお詫び申し上げます。
この建設がこの世界の誰かに役立つことを願っています。
よろしく、
ヴィカス・ゴータム