How to access MainThread elements from different thread? [duplicate] - python

This question already has answers here:
Updating GUI elements in MultiThreaded PyQT
(2 answers)
Closed 1 year ago.
I am creating a Server-Client GUI application in Python using PyQt5. Whenever a new clients is connected to server I need to display the client details at server side. I am using a separate thread for sockets. Whenever I call the client_connect function to add the widget at server side I get error due to which widget is not displayed. I think since the GUI and socket codes are in different threads due to this I am getting the error.
QObject::setParent: Cannot set parent, new parent is in a different thread
QObject::installEventFilter(): Cannot filter events for objects in a different thread.
QBasicTimer::start: QBasicTimer can only be used with threads started with QThread
QBasicTimer::start: QBasicTimer can only be used with threads started with QThread
QBasicTimer::start: QBasicTimer can only be used with threads started with QThread
QObject::startTimer: Timers can only be used with threads started with QThread
QBasicTimer::start: QBasicTimer can only be used with threads started with QThread
Main Function
if __name__ == "__main__":
thread1 = threading.Thread(target = ui.server_socket)
thread1.start()
client_connect Function - I have created a separate file for the widget and I am inserting the widget in tableWidget. It works if i directly call the function but if i call it from the socket code it gives me error.
def client_connect(self,clientid):
self.clientCount = self.clientCount + 1
self.clientList.append(clientid)
self.clientDict[clientid] = QtWidgets.QWidget()
self.clientDict[clientid].ui = clients()
self.clientDict[clientid].ui.setupUi(self.clientDict[clientid])
self.clientDict[clientid].ui.label_clientid.setText(str(clientid))
self.tableWidget_client.setRowCount(self.clientCount)
self.tableWidget_client.setCellWidget(self.clientCount-1,0,self.clientDict[clientid])
Socket programming
def start_socket(self):
self.ssock.listen(20)
while True:
conn, c_addr = self.ssock.accept()
print(conn,c_addr)
thread2 = threading.Thread(target=self.handle_client, args=(conn,c_addr))
thread2.start()
def handle_client(self, conn, c_addr):
try:
self.c = conn.recv(1024).decode(self.FORMAT)
thread3 = threading.Thread(target = self.client_connect, args = (self.c_id,))
thread3.start()
except socket.error as e:
print(e)

As you suspected, you shouldn't directly modify PyQt objects from different threads. You may read the docs about threads and objects.
Docs specifically mention that:
If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior. [.......] On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.
The way PyQt wants you to do it is to use Signals and Slots. Below is a small example of emitting a signal from worker's run function.
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
# Some Ui stuff is happening here
self.worker = Worker(self.startParm)
self.worker.client_connected.connect(self.display_client_info)
self.worker.start() # When you want to process a new client connection
def display_client_info(self, client_id):
# Code here should be similar to what you're trying to do in client_connect
class Worker(QThread):
def __init__(self):
super(Worker, self).__init__()
self.client_connected = pyqtSignal(int)
def run(self, clientid):
# The code you want to be executed in a thread
# For example whatever happens in handle_client, except in your design you're going
# through a middle thread and this is a basic example.
# Eventually emit client_connected signal with the client id:
self.client_connected.emit(client_id)
The main concepts to take from this:
Only modify PyQt objects from the main thread
Create signals and connect them to functions that will update UI for you in the main thread
Emit signals from within threads when you need to
Overriding QThread's run function is a more simple but can be limited way of using this. You may look into creating QObjects and using moveToThread function for more options.

Related

Slot method called in the wrong thread (pyqt)

This class suppose to handle a long task in a separate thread.
Despite moving my object to a new thread, and using queued connection, the signal is handled at the main gui thread instead of self.thread. The main gui thread is the thread that did called startit of course..
This is the code:
class DoLongProcess(QObject):
def __init__(self,task):
QObject.__init__(self)
self._task=task
self._realtask=None
self.thread = QThread()
self.moveToThread(self.thread)
self.thread.started.connect(self.run,Qt.QueuedConnection)
#Slot()
def run(self):
self._realtask()
def startit(self,*params):
self._realtask= partial(self._task,*params)
self.thread.start()
I use pyside6. I tried to to split __init__ into two methods and moving the thread from outside. Also tried without the QueuedConnection attribute (which suppose to do this exactly). None of this had an effect.
Do you know why it doesn't work as expected?

Python multithreading with pypubsub and wx

I have a program that is structured like this:
The GUI is made with wxPython and is in the Main Thread. After launching the application, the GUI thread creates Thread1, which creates a static class Class1, which creates Thread2.
Thread1 talks with the GUI using wx.PostEvent, and everything works fine. I need Thread1 to communicate also with Thread2, so I decided to do that using pyPubSub. Thread2 needs to work in the background because it contains some operations that are executed periodically, but it contains also a function (let's say my_func()) that Thread1 needs to call on certain events. I decided to put my_func() in Thread2 because I don't want it to stop the execution of Thread1, but that's exactly what happens: in Thread1 after some events I use pub.sendMessage("events", message="Hello") to trigger my_func(); Thread2 is structured like this:
class Thread2(Thread)
def __init__(self, parent):
super().__init__()
self.parent = parent
pub.subscribe(self.my_func, "events")
def run(self):
while True:
# do stuff
def my_func(self, message):
# do other stuff using the message
# call parent functions
The parent of Thread2 is Class1, so when I create the thread in Class1 I do:
self.t2 = Thread2(self)
self.t2.start()
Why does Thread2 stops the execution of Thread1?
To put in different words what was said in the comments, pypubsub's sendMessage is actually calling your listener function and thus waits for it to return before moving on. If this listener function takes a significant amount of time to run, then the behavior you obtain is an apparent "blocking" of your thread.
Here you probably want to 'send' a lightweight message to trigger the computation and 'listen' to the result in another place, in a 'non-blocking' fashion.

Why monitoring a keyboard interrupt in python thread doesn't work

I have a very simple python code:
def monitor_keyboard_interrupt():
is_done = False
while True:
if is_done
break
try:
print(sys._getframe().f_code.co_name)
except KeyboardInterrupt:
is_done = True
def test():
monitor_keyboard_thread = threading.Thread(target = monitor_keyboard_interrupt)
monitor_keyboard_thread.start()
monitor_keyboard_thread.join()
def main():
test()
if '__main__' == __name__:
main()
However when I press 'Ctrl-C' the thread isn't stopped. Can someone explain what I'm doing wrong. Any help is appreciated.
Simple reason:
Because only the <_MainThread(MainThread, started 139712048375552)> can create signal handlers and listen for signals.
This includes KeyboardInterrupt which is a SIGINT.
THis comes straight from the signal docs:
Some care must be taken if both signals and threads are used in the
same program. The fundamental thing to remember in using signals and
threads simultaneously is: always perform signal() operations in the
main thread of execution. Any thread can perform an alarm(),
getsignal(), pause(), setitimer() or getitimer(); only the main thread
can set a new signal handler, and the main thread will be the only one
to receive signals (this is enforced by the Python signal module, even
if the underlying thread implementation supports sending signals to
individual threads). This means that signals can’t be used as a means
of inter-thread communication. Use locks instead.

How come the main thread is blocked if .connect takes a lambda function?

I'm trying to let a button spin up a new thread that does nothing but sleep for 30 seconds. However, the main thread is blocked if the slot is a lambda function. Does anyone know why this is the case and not behaving what I was expecting it to be? Here's my code:
# ...
def setup(self):
# ...
self.pushButton_TestConnection.clicked.connect(self.process)
def process(self):
self.worker_thread = QtCore.QThread()
self.worker = Worker()
self.worker.moveToThread(self.worker_thread)
self.worker_thread.started.connect(lambda: self.worker.sleep(30))
self.worker_thread.start()
class Worker(QtCore.QObject):
def sleep(self, secs):
time.sleep(secs)
It works fine with the following
self.worker_thread.started.connect(self.worker.sleep)
self.worker_thread.start()
class Worker(QtCore.QObject):
def sleep(self):
time.sleep(30)
Thanks
In Qt the thread in which code is executed is determined by the thread affinity of the object receiving a signal. If you call a objects method directly from a different thread, it will be executed in the calling thread, no matter the thread affinity of the called object.
Lambdas and other python callables do not have a thread affinity (they're not QObjects after all, it's just a nice feature of PyQt allowing you to connect a signal to any python callable), so they will always be executed in the main (GUI) thread.
So in this case the lambda is executed in the GUI thread, so the worker.sleep call will also be executed there and will block it until the call returns.
To make this work, you need to connect the started signal directly to a slot of the Worker object, or communicate with the Worker using a signal you emit from the lambda.

How to send parameters to a Qthread

Im trying to send parameter to a Qthread that is not the main thread.
i have this object in my main thread and i want to send it to another thread:
q = Queue()
I want so send q to this thread:
class Sender(QtCore.QThread):
def __init__(self,q):
super(Sender,self).__init__()
self.q=q
def run(self):
while True:
try: line = q.get_nowait()
# or q.get(timeout=.1)
except Empty:
pass
else:
self.emit(QtCore.SIGNAL('tri()'))
Im trying this:
class Sender(QtCore.QThread):
def __init__(self,q):
super(Sender,self).__init__()
self.q=q
self.sender= Sender(q)
But im getting this error:
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)
How can i do this?
Please help!
There is no problem with your QThread subclass, and how you are setting it up to pass a Queue object. Though I do also recommend passing and setting an optional parent as the second parameter.
What you are mostly likely running into is you are passing objects that perform QtGui operations (drawing related) into your thread. If that is the case, you cannot call any QtGui drawing related methods. They all must be performed in the main thread. Do any data processing in other threads and then emit signals for the main thread to do widget updates.
Look for what you are sending into the queue, and specifically what you are doing with it inside of your thread, as a cue to the source of the error. Somewhere, you are doing something with a QTextCursor, which is trying to trigger and queue up a paint event.

Categories

Resources