Haven没有启动线程但是Python抛出异常并且线程已经开始了#39;

时间:2012-10-30 10:13:36

标签: python multithreading

我正在编写一个生产者 - 消费者应用程序。生产者线程开始正常,但是当我尝试启动消费者线程时,我得到一个异常。这是相关的代码:

#Producer threads
    for i in range(nThreads):
        self.producerThreads.append(MailThread(i, settings.MAX_EMAILS_PERPASS, self.toFetchQueue, self.rawEmailsQueue, self.stopEvent))
        self.producerThreads[i].start()
        logging.info('Started producer thread %d', i)

    #Consumer threads
    #for i in range(settings.MAX_CONS_THREADS):
    try:
        self.consumerThreads.append(ProcessThread(i, settings.STORE_DIRECTORY, settings.DELETE_ONPIPE, self.rawEmailsQueue, self.stopEvent))
        self.consumerThreads[i].start()
        logging.info('Started consumer thread %d', i)
    except Exception, e:
        logging.error('Failed to start consumer thread %s', str(e))

这是消费者类:

import logging, commands, threading, uuid, os, settings, Queue

class ProcessThread(threading.Thread):
"""
Class to process the emails. 
"""
def __init__(self, threadCount, storeDirectory, deleteOnPipe, rawEmailsQueue, stopEvent):
    self.threadCount = threadCount
    self.rawEmailsQueue = rawEmailsQueue
    self.stopEvent = stopEvent
    self.storeDirectory = storeDirectory
    self.deleteOnPipe = deleteOnPipe
    threading.Thread.__init__(self)

def run(self):
    logging.info('Run process for consumer thread %d', self.threadCount)

    while not self.stopEvent.is_set():
        try:
            emailContainer = rawEmailsQueue.get(False)
            logging.debug('Got a new email')

        except Queue.Empty:
            logging.debug('No emails in queue, going to sleep for a while')
            sleep(0.1)
            continue

处理代码的#Rest

我无法得到正确的缩进,在我的代码中没问题

1 个答案:

答案 0 :(得分:0)

这是一个愚蠢的错误(可能是因为我已经在PHP中编写了很多代码)。我已经像这样初始化了数组:

self.producerThreads = self.consumerThreads = []

两个阵列都指向相同的内存。