Your problem mostly stems from the fact that you aren't converting the returned sip.voidptr to an integer. If you instead print int(QThread.currentThreadId())
you get meaningful numbers out. In short what you were looking at was the address of the memory location where the threadId was being stored in, which obviously depends on the apps current memory usage. The contents of those memory addresses always agree though.
You might also be interested to know that the Python threading module gives you the same consistent information (See example below).
One final thing, I feel your app is not thread safe because you move your self.worker
object to a QThread, and then directly call a method from the main-thread when you click "run worker here". In my example below, I've instantiated a new worker object in that case just to be safe.
Also, please forgive this conversion of your example to PyQt4 and Python 2.7!
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSignal
import time
import sys
import threading
def logthread(caller):
print('%-25s: %s, %s,' % (caller, QtCore.QThread.currentThread(), int(QtCore.QThread.currentThreadId())))
print('%-25s: %s, %s,' % (caller, threading.current_thread().name, threading.current_thread().ident))
class Worker(QtCore.QObject):
done = pyqtSignal()
def __init__(self, parent=None):
logthread('worker.__init__')
super(Worker, self).__init__(parent)
def run(self, m=10):
logthread('worker.run')
for x in range(m):
y = x + 2
time.sleep(0.001)
logthread('worker.run finished')
self.done.emit()
class MainWindow(QtGui.QWidget):
def __init__(self, parent=None):
logthread('mainwin.__init__')
super(MainWindow, self).__init__(parent)
self.worker = Worker()
self.workerThread = None
self.btn = QtGui.QPushButton('Start worker in thread')
self.btn2 = QtGui.QPushButton('Run worker here')
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.btn)
layout.addWidget(self.btn2)
self.run()
def run(self):
logthread('mainwin.run')
self.workerThread = QtCore.QThread()
self.worker.moveToThread(self.workerThread)
self.worker.done.connect(self.workerDone)
self.btn.clicked.connect(self.worker.run)
self.btn2.clicked.connect(self.runWorkerHere)
self.workerThread.start()
self.show()
def workerDone(self):
logthread('mainwin.workerDone')
def runWorkerHere(self):
logthread('mainwin.runWorkerHere')
worker = Worker()
worker.done.connect(self.workerDone)
worker.run()
# self.worker.run()
if __name__ == '__main__':
app = QtGui.QApplication([])
logthread('main')
window = MainWindow()
sys.exit(app.exec_())