Reputation: 865
I'm trying to pass the contents of a variable to a function within a class that's run as a thread. How would I do this? Following is some pseudo code that should have the output following. The variable in question is p_number
.
class sessioning(Thread):
def run(self, p_number):
print p_number
p_number = 50885
for i in xrange(30):
sessioning().start(p_number)
p_number+=1
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
... Numbers in-between
50914
50915
Please note that this code is just an example, and I'm not actually performing overkill. This is a general question, but my specific application is to have it listen on ports within that range.
Upvotes: 1
Views: 108
Reputation: 6812
The Thread class has already implemented an easy way for you to invoke a function with arguments.
Here's a simple example:
def say_hi(name):
print "hello", name
Now you can use the Thread constructor to pass in the argument either by position or by name:
from threading import Thread
a = Thread(target=say_hi, args=("byposition",))
a.run()
b = Thread(target=say_hi, kwargs={"name": "byname"})
b.run()
This should correctly ouput:
hello byposition
hello byname
Ps: as a side note, since you are using multithreading, you cannot assume that the output will come in order like you showed in the example.
Upvotes: 0
Reputation: 13626
Pass it via constructor.
class Sessioning(Thread):
def __init__(self, p_number):
Thread.__init__(self)
self._pn = p_number
def run(self):
print(self._pn)
p_number = 50885
for i in xrange(30):
Sessioning(p_number).start()
p_number += 1
Upvotes: 4