I am planning a PySide Project which has a user authentication. Some of the operations of the program will require threads in order to keep the GUI responsive. Some of the operations which are done inside the threads require the user id or some other user data.
The main question is how to make those data available for the threads. The threads will not change the user id and there are only reading operations on the given user data.
The code below is a very simple mock up to illustrate the problem. The User class returns the user data if the login was successful. They will be stored as class variable inside the Interface class. As soon the Thread/QRunnable is initialized the user data are given to the worker and stored as class variable for the lifetime of the thread.
I couldn't find any clear answer to:
Is reading the variable inside the thread "thread safe" (As reading from a dict is an atomic operation it should be)
Is there a better way to make data like this available to a bigger project? e.g. Config files, User data...
Simple example:
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QObject, QRunnable, QThreadPool
class Worker(QRunnable):
def __init__(self, current_user):
super().__init__()
self.current_user = current_user
def run(self) -> None:
print(self.current_user)
class User():
def login(self, user: str, password: str):
return {'user_id': 1, 'user_name': f'{user}'}
class Interface(QMainWindow):
def __init__(self):
super().__init__()
self.thread_pool = QThreadPool.globalInstance()
self.user = User()
self.current_user = self.user.login('John Doe', '123456')
worker = Worker(self.current_user)
self.thread_pool.start(worker)
self.show()
if __name__ == '__main__':
app = QApplication([])
interface = Interface()
app.exec()
The ID of the user data stays always the same so all workers will operate on the same memory space as far as I understood