【发布时间】:2015-08-17 20:51:44
【问题描述】:
我是一名 php 开发人员,试图开发一个 python 多处理脚本。它正在创建一个需要 40,000 多个项目长的队列。队列填满,但我的进程无声无息地死去。在 2.6 和 2.7 中尝试过。
我一直在进行日志记录以尝试诊断正在发生的事情,但无济于事。在没有明显数据问题的随机条目上,所有子进程都将停止并且主线程将退出?注意:无论起点如何,它都是相同的条目失败,除非正在读取的条目少于 20 个。
有时它会输入 150 个条目,有时会在退出前输入 50 个条目。因为我需要它来做 40k,所以这是一个交易破坏者。该脚本执行 20 次左右没有问题,并记录正确的进程启动和退出消息。失败时,不会记录进程退出。
我的代码对发布过于敏感,但这是我使用的基本模型,取自多线程教程并转换为多处理模块。基本上,只是将“线程”替换为“多处理”,并使用多处理的队列而不是模块队列。
import Queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
【问题讨论】:
-
也许使用 pdb 调试器运行将有助于查明问题。使用说明位于docs.python.org/2/library/pdb.html,其他资源列表位于stackoverflow.com/questions/4228637/…。
-
由于您无法发布实际代码,您能否创建一个重现您的问题的示例?如果他们不能产生问题,人们很难帮助你。
-
您的“处理”是否可能引发异常?你什么都抓不到,你真的应该把
lock.release放在finally块中。 -
"它正在创建一个需要 40,000 多个项目长的队列。"这是经典的xy problem。
标签: python multithreading multiprocessing