您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python线程self._stop()'Event'对象不可调用

Python线程self._stop()'Event'对象不可调用

在上面提到的答案的注释中提到了该解决方案:

self._stop已被所使用Threading.thread

修改后的代码有效(带有注释的更改):

import sys
import threading
import time
import logging

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        print( "base init", file=sys.stderr )
        super(StoppableThread, self).__init__()
        self._stopper = threading.Event()          # ! must not use _stop

    def stopit(self):                              #  (avoid confusion)
        print( "base stop()", file=sys.stderr )
        self._stopper.set()                        # ! must not use _stop

    def stopped(self):
        return self._stopper.is_set()              # ! must not use _stop


class datalogger(StoppableThread):
    """
    """

    import time

    def __init__(self, outfile):
      """
      """
      StoppableThread.__init__(self)
      self.outfile = outfile
      print( "thread init", file=sys.stderr )

    def run(self):
      """
      """
      print( "thread running", file=sys.stderr )
      while not self.stopped():
        print( self.outfile , file=sys.stderr)
        time.sleep(0.33)
      print( "thread ending", file=sys.stderr )


test = datalogger("test.txt")
test.start()
time.sleep(3)
logging.debug("stopping thread")
test.stopit()                                      #  (avoid confusion)
logging.debug("waiting for thread to finish")
test.join()
python 2022/1/1 18:37:51 有513人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶