问题
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