2

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()
  • The first approach will be much simpler to comprehend and maintain later. – bereal Jan 29 '14 at 11:37
  • The second way share the same Queue between all Worker instances. The first way allows you to do that too, but also not to do that if you want .. – wim Jan 29 '14 at 11:38

1 Answers1

2

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).

bereal
  • 32,519
  • 6
  • 58
  • 104