Skip to content Skip to sidebar Skip to footer

Inheritance Threading.thread Class Does Not Work

I'm new in multithreading, so the answer is probably very simple. I'm trying to make two instances of one class and run them parallel. I've read that I can use class inheritance t

Solution 1:

The documentation for threading says that you should override the run() method, and then use the start() method to begin execution on a new thread. In your case, your code should be:

classHello(threading.Thread):
    def__init__(self, min, max):
        self.min, self.max = min, max
        threading.Thread.__init__(self)

    defrun(self):
        time.sleep(self.max)

        for i inrange(1000):
            print random.choice(range(self.min, self.max))

# This creates the thread objects, but they don't do anything yet
h = Hello(3,5)
k = Hello(0,3)

# This causes each thread to do its work
h.start()
k.start()

Solution 2:

Python's regular implementation of a thread already knows how to run a task, so unless you're creating a special kind of thread (not a special kind of task) - what you probably want is to use the regular thread:

deftask(_min, _max): # 'min' and 'max' are actual functions!
    time.sleep(_max)
    for _ inrange(1000):
        print random.choice(range(_min,_max))

And now create a thread to run the task:

t1 = threading.Thread(target=task, args=(3, 5,))
t2 = threading.Thread(target=task, args=(3, 5,))

t1.start()
t2.start()

Post a Comment for "Inheritance Threading.thread Class Does Not Work"