SIGNAL(Const QByteArray&) Thread Safety Between 2 Threads (QueuedConnection)



  • Lets say I have 2 Threads: A & B (actually objects moved to different threads)

    Thread A will receive a slot call containing an object to serialize to a QByteArray. After serialization, It appends that QByteArray to an existing Member QByteArray that constitutes an outbound buffer to be sent to a TcpSocket. Thread A then emits a const reference to the outbound buffer.
    emit Send(const QByteArray& m_OutBoundByteArray)

    Thread B has a slot called SendData that is connected to Thread A's Send Signal.
    void SendData(const QByteArray& outboundData)
    {
    TcpSocket->write(outboundData).
    }

    My Question is, what happens if Thread A appends to that m_OutBoundByteArray while Thread B is in the middle of writing it to the TcpSocket? If the member variable m_OutBoundByteArray in thread A is grows in size, does reallocation occur underneath the hood which would cause Thread B to read invalid memory? Or does the const reference QByteArray in the slot call to thread B remain invariant and the memory will be guaranteed to be valid?

    Additionally, Thread A will only Append (Never Remove) elements to the m_OutboundByteArray while Thread B is reading from the const reference in the slot call.


  • Qt Champions 2016

    @blackflame7000
    Hello,

    My Question is, what happens if Thread A appends to that m_OutBoundByteArray while Thread B is in the middle of writing it to the TcpSocket?

    Both worker objects will work on their own data copies. When you have a signal-slot connection across threads the arguments are packed and the slot invocation is differed through a event loop event. This means that when you call emit Send(const QByteArray & m_OutBoundByteArray) your byte array will be copied and and event will be put in the receiver object's thread's event loop. That event, when processed, will be your call to the slot.

    Kind regards.



  • @kshegunov
    Thank you for clarifying that scenario! It is very much appreciated.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.