Is communicating with a std::jthread via a std::atomic<bool> flag set by slots safe?
-
When watching a recorded online presentation named "Multithreading with Qt" by Giuseppe D’Angelo I notice that he recommends to avoid adding slots to
QThread.
In the example he uses (at 50 minutes) hisQThreadhas aSocketmember variable that he creates in therun()of his thread. Not sure which class Socket actually is meant to be, but I am guessingQTcpSocket.
His thread has a slot and this will be called from the main thread since aQThreadhas affinity with the main thread (when it is created there).
I understand that this is a problem sinceQTcpSocketis reentrant but not thread safe.
I guess the same goes forQSerialPort? I should never use these in more than one thread?In my code I have a class like this:
class Thread : public QObject { Q_OBJECT public: Thread(); // will start threadFunction() in m_thread public slots: void start() { m_running = true; } void stop() { m_running = false; } private: void threadFunction(); // runs a forever loop and if m_running do some work std::atomic<bool> m_running{ false }; std::jthread m_thread; };The slots
start()andstop()will be called from another non main thread. Thread is created in the main thread.Is this safe?
-
When watching a recorded online presentation named "Multithreading with Qt" by Giuseppe D’Angelo I notice that he recommends to avoid adding slots to
QThread.
In the example he uses (at 50 minutes) hisQThreadhas aSocketmember variable that he creates in therun()of his thread. Not sure which class Socket actually is meant to be, but I am guessingQTcpSocket.
His thread has a slot and this will be called from the main thread since aQThreadhas affinity with the main thread (when it is created there).
I understand that this is a problem sinceQTcpSocketis reentrant but not thread safe.
I guess the same goes forQSerialPort? I should never use these in more than one thread?In my code I have a class like this:
class Thread : public QObject { Q_OBJECT public: Thread(); // will start threadFunction() in m_thread public slots: void start() { m_running = true; } void stop() { m_running = false; } private: void threadFunction(); // runs a forever loop and if m_running do some work std::atomic<bool> m_running{ false }; std::jthread m_thread; };The slots
start()andstop()will be called from another non main thread. Thread is created in the main thread.Is this safe?
@andyP said in Is communicating with a std::jthread via a std::atomic<bool> flag set by slots safe?:
Is this safe?
Yes, but it's safe even without any Qt.
-
@andyP said in Is communicating with a std::jthread via a std::atomic<bool> flag set by slots safe?:
Is this safe?
Yes, but it's safe even without any Qt.
@Christian-Ehrlicher: thank you for your help!