spacepaste

  1.  
  2. import sys
  3. import PyQt5
  4. from PyQt5.QtWidgets import *
  5. from PyQt5.QtCore import *
  6. from queue import Queue
  7. import time
  8. def doJob(data_in):
  9. print('doJob: processing data',data_in)
  10. time.sleep(int(data_in))
  11. return data_in
  12. class WorkerThread(QThread):
  13. def __init__(self,func,jobqueue,outqueue,parent=None):
  14. QThread.__init__(self,parent)
  15. self.func=func
  16. self.jobqueue=jobqueue
  17. self.outqueue=outqueue
  18. self.timer=QTimer()
  19. self.timer.moveToThread(self)
  20. self.timer.timeout.connect(self.stopthread)
  21. self._running=True
  22. def run(self):
  23. self.timer.start(4000)
  24. #loop = QEventLoop()
  25. #loop.exec_()
  26. while self._running:
  27. args=self.jobqueue.get()
  28. rec=self.func(*args)
  29. self.jobqueue.task_done()
  30. self.outqueue.put(rec)
  31. def stopthread(self):
  32. self._running=False
  33. self.quit()
  34. print('stopthread called')
  35. self.outqueue.put(None)
  36. class MainWindow(QMainWindow):
  37. def __init__(self):
  38. super(self.__class__, self).__init__()
  39. frame=QWidget()
  40. self.setCentralWidget(frame)
  41. hl=QVBoxLayout()
  42. frame.setLayout(hl)
  43. self.startBtn=QPushButton()
  44. self.startBtn.setText('Start')
  45. self.startBtn.clicked.connect(self.pressedStartBtn)
  46. hl.addWidget(self.startBtn)
  47. self.show()
  48. def pressedStartBtn(self):
  49. self.jobq=Queue()
  50. self.outq=Queue()
  51. for ii in range(20):
  52. self.jobq.put(str(ii))
  53. self.worker = WorkerThread(doJob,self.jobq,self.outq,self)
  54. self.worker.start()
  55. results=[]
  56. while self.outq.qsize():
  57. resii=self.outq.get()
  58. results.append(resii)
  59. def main():
  60. # a new app instance
  61. app = QApplication(sys.argv)
  62. form = MainWindow()
  63. form.show()
  64. sys.exit(app.exec_())
  65. if __name__ == "__main__":
  66. main()
  67.