I'm trying to create a program which has Main class (which has Permanently counting method and Permanently emitting signal Received from Worker class method) and Worker class (which is counting number and emitting to Main class Permanently)
I'm new to programming So I don't know asynchronous or parallel program But I have to use signal/slot That's why I decided using pyqt
When I used QThread It was blocking main_cnt()
class Worker(QThread):
tr_pass = pyqtSignal(int)
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
print("Worker cnt : ", cnt)
self.tr_pass.emit(cnt)
time.sleep(2)
class Main:
def __init__(self):
self.worker = Worker()
self.worker.tr_pass.connect(self.worker_connect)
self.worker.run()
self.main_cnt()
def main_cnt(self):
cnt = 0
while True:
cnt += 1
print("main cnt : ", cnt)
time.sleep(3)
def worker_connect(self, df):
print("Connected by Worker : ", df)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Main()
app.exec_()
So I used moveToThread It works asynchronously But It doesn't work well
Terminal indicates like this and 'self.worker_.tr_pass.connect(self.worker_connect)' doesn't work
- main cnt : 1
- Worker cnt : 1
- Worker cnt : 1
- Worker cnt : 2
- main cnt : 2
- Worker cnt : 3
- Worker cnt : 4main cnt : 3
- Worker cnt : 5
- main cnt : 4
- main cnt : 4
- Worker cnt : 6
class Worker_(QObject):
tr_pass = pyqtSignal(int)
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
print("Worker cnt : ", cnt)
self.tr_pass.emit(cnt)
time.sleep(2)
class Main:
def __init__(self):
self.worker_ = Worker_()
self.thread = QThread()
self.worker_.moveToThread(self.thread)
self.thread.started.connect(self.worker_.run)
self.worker_.tr_pass.connect(self.worker_connect)
self.thread.start()
self.main_cnt()
def main_cnt(self):
cnt = 0
while True:
cnt += 1
print("main cnt : ", cnt)
time.sleep(3)
def worker_connect(self, df):
print("Connected by Worker : ", df)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Main()
app.exec_()
How can I solve this problem I appreciate your answer