python - 在Python中动态实例化类

标签 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)

任何建议都会很棒。

最佳答案

简单地使用:

new_worker_thread = worker()

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

有关线程的更多信息可以在这里找到:http://www.tutorialspoint.com/python/python_multithreading.htm

非常有用的教程!

关于python - 在Python中动态实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11075710/

相关文章:

c++ - 当方法只接受一个参数时,如何比较两个对象?

Java序列化问题

python - 使用浏览器用户代理检查网站是否在 python 中响应

python - Python GTK+ 3 教程 Hello World 中没有名为 'gi' 的模块

python - 如何使用 GraphQL 模式进行类似 JSON 模式的数据验证?

C 多线程和真实路径

c++ - 在 C++ 中向主线程报告线程进度

Python 列表和生成

java - 方法中是否需要 "volatile"?

java - 从类中调用已实现的接口(interface)重写方法