Реализация базового процесса очереди / потока в Python
Ищем глазные яблоки, чтобы убедиться, что следующий кусок псевдо-питона имеет смысл. Я надеюсь создать несколько потоков, чтобы реализовать некоторые функции inproc как можно быстрее. идея состоит в том, чтобы порождать потоки в главном цикле, поэтому приложение будет запускать потоки одновременно в параллельном / параллельном режиме.
chunk of code
-get the filenames from a dir
-write each filename ot a queue
-spawn a thread for each filename, where each thread
waits/reads value/data from the queue
-the threadParse function then handles the actual processing
based on the file that's included via the "execfile" function...
# System modules
from Queue import Queue
from threading import Thread
import time
# Local modules
#import feedparser
# Set up some global variables
appqueue = Queue()
# more than the app will need
# this matches the number of files that will ever be in the
# urldir
#
num_fetch_threads = 200
def threadParse(q)
#decompose the packet to get the various elements
line = q.get()
college,level,packet=decompose (line)
#build name of included file
fname=college+"_"+level+"_Parse.py"
execfile(fname)
q.task_done()
#setup the master loop
while True
time.sleep(2)
# get the files from the dir
# setup threads
filelist="ls /urldir"
if filelist
foreach file_ in filelist:
worker = Thread(target=threadParse, args=(appqueue,))
worker.start()
# again, get the files from the dir
#setup the queue
filelist="ls /urldir"
foreach file_ in filelist:
#stuff the filename in the queue
appqueue.put(file_)
# Now wait for the queue to be empty, indicating that we have
# processed all of the downloads.
#don't care about this part
#print '*** Main thread waiting'
#appqueue.join()
#print '*** Done'
Мысли / комментарии / указатели приветствуются...
Спасибо
1 ответ
Если я правильно понимаю: вы создаете много потоков, чтобы сделать вещи быстрее.
Это работает, только если основная часть работы, выполняемой в каждом потоке, выполняется без удержания GIL. Так что, если есть много данных, ожидающих данных из сети, с диска или чего-то в этом роде, это может быть хорошей идеей. Если в каждой из задач используется много ЦП, это будет работать почти так же, как на одноядерном компьютере с 1 ЦП, и вы можете выполнять их последовательно.
Я должен добавить, что то, что я написал, верно для CPython, но не обязательно для Jython/IronPython. Кроме того, я должен добавить, что если вам нужно использовать больше процессоров / ядер, то вам может помочь многопроцессорный модуль.