在Python中动态实例化类

时间:2012-06-17 23:51:31

标签: python multithreading class

我想基于数据库查询动态地将threading.Thread类添加到线程queue。这可能吗?

例如:

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)

任何建议都很棒。

1 个答案:

答案 0 :(得分:3)

只需使用:

new_worker_thread = worker()

这会实例化一个新的工作线程。在此之后,您可以启动并将其放入队列中。

有关线程的更多信息,请访问:http://www.tutorialspoint.com/python/python_multithreading.htm

非常有用的教程!