2012-06-17 70 views
1

我想動態地將threading.Thread類添加到基於數據庫查詢的線程queue。那可能嗎?在Python中動態實例化類

例如:

import threading, Queue 

class worker(threading.Thread): 
    def run(self): 
     while True: 
      print 'doing stuff' 

# get jobs from db 
jobs = list(db.Jobs.find()) 

q = Queue.Queue(5) 
for job in jobs: 
    # instantiate a worker thread here.. don't know how to do this 
    ... 
    # start new worker thread 
    new_worker_thread.start() 
    # then add the worker to the queue 
    q.put(new_worker_thread) 

任何意見將是真棒。

+2

值得注意的是,[PEP-8](http://www.python.org/dev/peps/pep-0008/)(Python風格指南)建議'CapWords'保留給類,'lowercase_with_underscores '用於變量。你可能想要遵循這個來讓你的代碼更具可讀性。 –

+2

Ahm,new_worker_thread = worker()有什麼不對? –

+0

哦,對,因爲實例化一個同名的worker不會覆蓋現有的對象..我現在認識到 – MFB

回答

3

只需使用:

new_worker_thread = worker() 

此實例化一個新的工作線程。在此之後,您可以開始並將其放入隊列中。

上螺紋部分的更多信息可以在這裏找到:http://www.tutorialspoint.com/python/python_multithreading.htm

非常有用的教程!

+0

哦對,因爲實例化一個同名的worker不會覆蓋現有的對象..我意識到現在我知道 – MFB

+0

準確而且原因在於你將對象存儲在一個隊列中,以便以後可以訪問它們。 – tabchas