简体   繁体   中英

QThread:How to use protected static functions

I learn from the following links that sub classing a QThread is not a correct way of using it...the proper way is to subclass the QObject and then move the object of QObject class to the respective thread using moveToThread() function...i followed the following links.. link 1 and link 2 ...but my question is then how will i be able to use msleep() and usleep() protected static functions ? or will i use QTimer to make a thread wait for some time ?

No need for timers. For waiting, Qt provides QWaitCondition. You can implement something like this:

#include <QWaitCondition>
#include <QMutex>

void threadSleep(unsigned long ms)
{
    QMutex mutex;
    mutex.lock();
    QWaitCondition waitCond;
    waitCond.wait(&mutex, ms); 
    mutex.unlock();
}

This is a normal function. You can of course implement it as a member function too, if you want (it can be a static member in that case.)

One solution would be to create a timer:

class Worker: public QObject
{
///...

private slots:
void doWork()
{
    //...
    QTimer::singleShot(delay, this, SLOT(continueDoingWork()));
}

void continueDoingWork()
{
}
};

Sometimes, you only need to run an operation in a different thread and all this event loops and threads are overhead. Then you can use QtConcurent framework:

class Worker
{
public:
void doWork()
{
//...
}
} worker;

//...

QtConcurent::run(worker, &Worker::doWork);

Then, I usually use mutexes to simulate the sleep operations:

QMutex m;
m.lock();
m.tryLock(delay);

The canonical answer is "use signals and slots."

For example, if you want a QObject in a thread to "wake itself up" after a certain period of time, consider QTimer::singleShot() , passing in the slot as the third argument. This can be called from the slot in question, resulting in periodic execution.

You can't let a different thread sleep without cooperation of this thread, thats the reason the member functions of QThread are protected. If you want to sleep a different thread you need to use a condition variable or a timer inside

If you want so sleep the current thread with usleep() , the simplest way is to subclass it - its perfectly fine as long as you don't need QThreadPool , a thread local event loop or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM