2012-06-17 48 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