Question

I'm designing an Qt application which performs ARP scan in the local network. I have my thread class here (pseudo code):

class worker:public QThread
{
    run()
    {
        .......some code;

        .......some code;
    }

    slot function1()
    {
        .......some code;
        sleep(5);
        .......some code;
    }

    slot function2()
    {
        .......some code;

        .......some code;
    }
}

I know the sleep function will block it's own caller for certain amount of time, but, will the sleep function in function1 above block the other two as well because they belong to one QThread object? Function1 and function2 are slots which only been triggered by connected signals.

Thanks!

Was it helpful?

Solution

The simple answer to your question is yes, calling sleep in that situation will block the thread and so will stop messages in the thread's message loop from being processed.

Part of the problem you have stems from the fact that unless you're wanting to re-write the code of how Qt handles threads, you should not be inheriting from QThread. "You're doing it wrong!"

What you should do is create worker objects derived from QObject and move those to a QThread: -

class WorkerObject : public QObject
{
    Q_OBJECT

    public:
        WorkerObject(QObject* parent = NULL);

    private:

    private slots:
        void DoWork();
};


QThread* thread = new QThread;
WorkerObject* worker = new WorkerObject(parent);

worker->moveToThread(thread);
// Qt 5 connect syntax
connect(thread, &QThread::started, worker, &WorkerObject::DoWork);
connect(thread, &QThread::finished, thread, &QThread deleteLater);

thread->start();

Done this way, you can create multiple worker objects and move any number of them to the new thread, rather than insisting on a new thread per worker object. If you're creating more threads than the number of processor cores available, you're not going to benefit from using those extra threads.

You can read more about how to use QThreads here.

Finally, if you're having to call sleep in the thread, then perhaps your design is wrong. If you wanting to wait, perhaps using QMutex would be a better option.

OTHER TIPS

The answer to this depends on the connection type. If the connection is made between two objects owned by the same thread, they will not be concurrent. If connections are made between two objects that were created on different threads, they can be concurrent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top