【问题标题】:implementing a basic queue/thread process within python在 python 中实现一个基本的队列/线程进程
【发布时间】:2010-07-28 20:11:23
【问题描述】:

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

感谢想法/cmets/指针...

谢谢

【问题讨论】:

    标签: python multithreading queue parallel-processing simultaneous


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 2023-03-10
      • 2018-01-23
      相关资源
      最近更新 更多