Why does the instance need to be recreated when restarting a thread?

前端 未结 3 862
时光说笑
时光说笑 2020-12-09 18:32

Imagine the following classes:

Class Object(threading.Thread):
    # some initialisation blabla
    def run(self):
        while True:
            # do somet         


        
相关标签:
3条回答
  • 2020-12-09 19:03

    The reason why threading.Thread is implemented that way is to keep correspondence between a thread object and operating system's thread. In major OSs threads can not be restarted, but you may create another thread with another thread id.

    If recreation is a problem, there is no need to inherit your class from threading.Thread, just pass a target parameter to Thread's constructor like this:

    class MyObj(object):
        def __init__(self):
            self.thread = threading.Thread(target=self.run)
        def run(self):
            ...
    

    Then you may access thread member to control your thread execution, and recreate it as needed. No MyObj recreation is required.

    0 讨论(0)
  • 2020-12-09 19:12

    I believe, that has to do with how Thread class is implemented. It wraps a real OS thread, so that restarting the thread would actually change its identity, which might be confusing.

    A better way to deal with threads is actually through target functions/callables:

    class Worker(object):
        """ Implements the logic to be run in separate threads """
        def __call__(self):
            #  do useful stuff and change the state
    
    class Supervisor():
        def run(self, worker):
            thr = None
            while True:
                if not thr or not thr.is_alive():
                    thr = Thread(target=worker)
                    thr.daemon = True
                    thr.start()
                thr.join(1)  # give it some time
    
    0 讨论(0)
  • 2020-12-09 19:19

    See here: http://docs.python.org/2/library/threading.html#threading.Thread.start

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the same thread object.

    A thread isn't intended to run more than once. You might want to use a Thread Pool

    0 讨论(0)
提交回复
热议问题