创建新线程后如何关闭正在运行的线程

时间:2019-05-17 23:18:28

标签: python multithreading pyqt5 runnable

我正在尝试创建一个价格行情自动收录器,每2秒刷新一次。

如何在创建新线程后取消上一个线程(在调用run_worker()之后创建新线程)

我试图通过某种方式从外部访问self._flag以关闭线程,但是如何访问当前正在运行的线程并关闭它呢?

def run_worker(self):
    print("run_worker")
    symbol = str(self.ui.pair_combo.currentText())
    worker = Worker(self.execute_this_fn, symbol)
    worker.signals.result.connect(self.print_output)
    worker.signals.finished.connect(self.thread_complete)
    self.threadpool.start(worker)

class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)


class Worker(QRunnable):
    def __init__(self, fn, *argv, **kwargs):
        super(Worker, self).__init__()
        self.fn = fn
        self.argv = argv
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        self.c = Client(api_key="account-xxx", api_secret="xxx", sandbox=True)

    @pyqtSlot()
    def run(self):
        asset = self.argv[0]
        self._flag = True
        try:
            while self._flag:
                # The price of the LAST executed trade on the exchange
                result = list(self.c.get_ticker(asset).values())[3]
                print("result " + result)
                time.sleep(2)
                if not self._flag:
                    break
            else:
                self._flag = False
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result) # Return the result of the processing
        finally:
            self.signals.finished.emit() #done

每次调用run_worker函数时(取决于组合框中的currentText),都会产生一个新线程。

0 个答案:

没有答案