0

If i define a python thread extending threading.Thread class and overriding run I can then invoke run() instead of start() and use it in the caller thread instead of a separate one.

i.e.

class MyThread(threading.thread):
    def run(self):
        while condition():
            do_something()

this code (1) will execute "run" method this in a separate thread

t = MyThread()
t.start()

this code (2) will execute "run" method in the current thread

t = MyThread()
t.run()

Are there any practical disadvantages in using this approach in writing code that can be executed in either way? Could invoking directly the "run" of a Thread object cause memory problems, performance issues or some other unpredictable behavior?

In other words, what are the differences (if any notable, i guess some more memory will be allocated but It should be negligible) between invoking the code (2) on MyThread class and another identical class that extends "object" instead of "threading.Tread"

I guess that some (if any) of the more low level differences might depend on the interpreter. In case this is relevant i'm mainly interested in CPython 3.*

2 Answers 2

1

There will be no difference in the behavior of run when you're using the threading.Thread object, or an object of a threading.Thread's subclass, or an object of any other class that has the run method:

threading.Thread.start starts a new thread and then runs run in this thread.

run starts the activity in the calling thread, be it the main thread or another one.

If you run run in the main thread, the whole thread will be busy executing the task run is supposed to execute, and you won't be able to do anything until the task finishes.

That said, no, there will be no notable differences as the run method behaves just like any other method and is executed in the calling thread.

Sign up to request clarification or add additional context in comments.

Comments

0

I looked into the code implementing threading.Thread class in cpython 3. The init method simply assigns some variables and do not do anything that seems related to actually create a new thread. Therefore we can assume that it should be safe use a threading.Thread object in the proposed manner.

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.