python threading - best way to pass arguments to threads

不问归期 提交于 2021-02-10 13:43:32

问题


I was wondering what would be the best way, performance wise, to pass shared arguments to threads (e.g. an input Queue).

I used to pass them as arguments to the __init__ function, because that's what I saw in most of the examples out there in the internet. But I was wondering whether it would be faster to set them as class variables, is there a reason not to do that?

Here is what I mean:

class Worker(threading.Thread):
   def __init__(self, in_q):
       self.in_q = in_q

or:

class Worker(threading.Thread):
   in_q = None
   def __init__(self):
       ...
...
def main():
   Worker.in_q = Queue.Queue()

回答1:


Class attributes are sometimes called "static" for a reason. They are part of the static model structure and tell something about the classes. Attributes tell something about the object in the runtime. This does not apply to your case.

For example, at some point you may want to have, e.g. two separate groups of workers running in parallel, but sharing different queues. The design with the static attributes will prevent you from doing that. Basically, that's a slightly disguised global variable with the same drawbacks (implicit coupling, encapsulation leakage etc).



来源:https://stackoverflow.com/questions/21429819/python-threading-best-way-to-pass-arguments-to-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!