1

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.

Pseudo

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

Wanted Output

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Référence

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.