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

前端 未结 3 863
时光说笑
时光说笑 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: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
    

提交回复
热议问题