0

処理したいものの600K以上の行を含むファイルがあります。
そのため、マルチスレッドを使用してプロセスを高速化します。
しかし、問題は、たとえば、スレッド数として50を使用し、50行を処理した後、スクリプトは他に何もしないことです。終了したり、他に何も表示されません。

これは参照用の私のコードです:

#!/usr/bin/env python

from __future__ import print_function
import re
import sys
from Queue import *
from threading import Thread, Lock

#struct parameters
if len(sys.argv) != 3:  # the program name and the two arguments
    # stop the program and print an error message
    sys.exit("Usage: python " + sys.argv[0] + " filename maxthreads")

accountlist = sys.argv[1]
maxthreads = int(sys.argv[2])

def dojob(email, password):
    #here is some job to process all my users data
    #end dojob

#this function will process the items in the queue, in serial
def processor():
    if queue.empty() == True:
        print ("the Queue is empty!")
        sys.exit(1)
    try:
        job = queue.get()
        job = job.strip('\r\n')

        newdata = job.split(':')

        email = newdata[0]
        password = newdata[1]

        #pass to dojob and process
        print("Processing:", email)

        dojob(email, password)

        queue.task_done()

    except:
        print ("Failed to operate on job")

#set variables
queue = Queue()
threads = maxthreads

#a list of job items. you would want this to be more advanced,like reading from a file or database
jobs = open(accountlist)

#iterate over jobs and put each into the queue in sequence
for job in jobs:
    print ("inserting job into the queue:", job)
    queue.put(job)

#start some threads, each one will process one job from the queue
for i in range(threads):
    th = Thread(target=processor)
    th.setDaemon(True)
    th.start()

#wait until all jobs are processed before quitting
queue.join() 

どんな考えでも、それがプロセスを停止するだけである理由です。

サンプル出力:

 #for example thread is 2
 inserting job into queue: user@domain.com
 inserting job into queue: user2@domain.com
 inserting job into queue: another@domain.com
 (...until the end of the file...)
 #once everything was added to the queue, is starts processing.
 processing: user@domain.com
 processing: user2@domain.com
 #then here the problem occurs, it doesnt do anything else.
 #it doesnt continue to the next queued job.
4

1 に答える 1

3

内部にループが必要なようですprocessor()

def processor():
    while not queue.empty():
        try:
            job = queue.get()
            ...

それ以外の場合、すべてのスレッドが1つのジョブを処理して停止します。

プロセスを高速化するためにマルチスレッドを使用しています。

処理の性質に応じて、複数のスレッドを使用することでスピードアップが得られる場合と得られない場合があります。これは、グローバルインタープリターロック(GIL)と関係があります。GILが原因でスピードアップが得られない場合は、multiprocessingモジュールの使用を検討することをお勧めします。

于 2012-12-07T22:28:25.957 に答える