poppypope 2020-05-24 08:40 采纳率: 0%
浏览 1080

python中qthread多线程终止任务的问题

任务WORK在thread里面运行后,如果想停止任务(而不是简单终止线程),用线程安全的方式用槽信号来触发任务停止条件时,不起作用,因为线程内需要等任务(dowork)自然完成后,才会接收其他槽信号队列。如果直接用跨线程的方式执行实例self.work.stop,反而能够立即停止任务。只是隐约感觉这种方式不太正规,请问有没有其他方式?

class Work(QObject):
   update_process = pyqtSignal(int)
   update_completed = pyqtSignal()

   .....ini_thing....

   def dowork(self):
       self.var = 0
       while self.var < 10 and self._running == True
          self.var += 1
          self.update_process.emit(self.var)
       self.update_completed.emit()  # -----------任务结束

   def stopwork(self):
       self._running = false

class UiTest(QDialog):
   .....UI-thing....

  self.work = Work()
  self.thread = QThread()
  self.work.moveToThread(self.thread)

  self.thread.started.connect(self.work.dowork)
  self.work.update_process.connect(self.currentStep.setValue)
  self.worker.update_completed.connect(lambda:print('work finished'))

  self.btnDoWork.clicked.connect(self.work.dowork)
1. self.btnStopWork.clicked.connect(self.work.stopwork)[/color] -- 通过槽触发任务
2. self.btnStopWork.clicked.connect(self.stopwork)[/color] -- 直接跨线程介入任务

  self.btnStopThread.clicked.connect(self.stop_thread)
  self.btnStartThread.clicked.connect(self.start_thread)
  self.thread.finished.connect(lambda: print('thread finished'))

  def start_thread(self):
     self.thread.start()
 def stop_thread(self):
     self.thread.quit()
     self.thread.wait()

** def stop_work(self): -------------直接跨线程介入任务
     self.work.stopwork**


。。。。APP Thing。。。。。。。
  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2020-09-18 14:43
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog