0

寻找一些眼球来验证以下伪 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'

想法/评论/指针表示赞赏......

谢谢

4

1 回答 1

0

如果我理解正确:您会产生大量线程以更快地完成工作。

这仅在每个线程中完成的工作的主要部分在没有持有 GIL 的情况下才有效。因此,如果有大量等待来自网络、磁盘或类似设备的数据,这可能是一个好主意。如果每个任务都使用大量 CPU,这将非常像在单核 1-CPU 机器上运行,您不妨按顺序执行它们。

我应该补充一点,我写的内容适用于 CPython,但不一定适用于 Jython/IronPython。另外,我应该补充一点,如果您需要使用更多的 CPU/内核,那么多处理模块可能会有所帮助。

于 2010-07-28T20:21:57.930 回答