2012-10-30 23 views
0

我正在編寫一個生產者 - 消費者應用程序。生產者線程開始正常,但是當我嘗試啓動消費者線程時,出現異常。下面是相關的代碼:還沒開始線程但Python拋出異常'線程已經啓動'

#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的處理代碼

我無法得到正確的縮進,這是在我的代碼罰款

+0

嘗試在啓動消費者線程之前將i設回0。這是必要的,因爲你刪除了for循環。 – Tim

回答

0

這是一個愚蠢的錯誤(可能是因爲我已經用PHP編碼了很多)。我已經初始化了這樣的陣列:

self.producerThreads = self.consumerThreads = [] 

兩個陣列都指向相同的內存。