1

I am writing a Qt/C++ program which receives data from a socket. I found that I was losing the readyRead signal because my slot was taking too long to analyze the incoming data. So now I've paired it down to the minimum:

void test::inputAvailable()
{
    while (m_tcpSocket->bytesAvailable())
        m_inputBuffer += m_tcpSocket->readAll();
    emit(datawaiting());
}

My questions are:

  1. Do I need to protext the m_inputBuffer variable with a mutex? Since this slot will be appending to it, while my main program may be removing data from it.
  2. Would a mutex slow down my slot too much since I need it to be quick. (to avoid losing a readyRead signal)
  3. Is the emit (last line) the right way to signal my program to analyze the incoming data? Or does this cause my program to re-enter the event loop while still in the slot (causing a signal to be lost)

I've read this similar question but no one has given a real answer.

Community
  • 1
  • 1
TSG
  • 4,242
  • 9
  • 61
  • 121
  • Do you use explicit multithreading? Because otherwise there's no synchronization needed. Signals are normal function calls and don't cause events to be processed. – Frank Osterfeld Nov 10 '13 at 17:58
  • I don't use threads related to the variables/methods I'm asking about (I have another unrelated thread in the program). I think that's what's confusing me. If a signal comes in while my program is manipulating a particular variable, and the slot also manipulates that variable, how does the event loop know what to do? Does it let the method complete first, or interrupt to run the slot method? When will it run the slot method? – TSG Nov 10 '13 at 21:37
  • 1
    The event loop doesn't do any multithreading. If your code is executed, the signal won't be delivered until your code completes and the control returns to the event loop. – Frank Osterfeld Nov 11 '13 at 08:03

2 Answers2

0
  1. Since it happen the same time some kind of variable access synchronization would be useful. Otherwise it could yield undefined behavior.
  2. That depends how long main program will occupy synchronized variable.
  3. Qt signals and slots are placed in event loop queue hence emitting datawaiting() n times you will end up with n times executed slot paired with that particular signal.
igleyy
  • 605
  • 4
  • 16
-1

Why share global variables, introduce synchronization etc. when you could simply read into a variable and pass it to the handler.

void test::inputAvailable()
{
    while (m_tcpSocket->bytesAvailable())
        QByteArray data  += m_tcpSocket->readAll();
    emit datawaiting(data);
}
goblinjuice
  • 3,184
  • 24
  • 26