[Qt-interest] Delay of code execution

K. Frank kfrank29.c at gmail.com
Wed Apr 14 03:59:06 CEST 2010


Hi Matthias -

Hmm...

I tried your method (for educational purposes only), and I found that it
worked both in my main gui thread, and in a separate thread I created.

On Tue, Apr 13, 2010 at 1:00 PM, Sean Harmer
<sean.harmer at maps-technology.com> wrote:
> On Tuesday 13 Apr 2010 16:09:49 Matthias Pospiech wrote:
>> I was using the following code:
>>
>> --- delay.h ----
>> ...
>> then I found that the following should be possible as well:
>>
>> --- delay.h ----
>> #include <QtCore/QThread>
>>
>> class SleeperThread : public QThread
>> {
>> public:
>>     static void msleep(unsigned long msecs)
>>     {
>>         QThread::msleep(msecs);
>>     }
>> };

Okay, I get this.  Derive publicly from QThread, and write the public, static
forwarding function msleep.  This, in effect, exposes QThread's protected,
static msleep function to the outside world.

>> inline void delay(long ms)
>> {
>>        SleeperThread::msleep(ms);
>> }
>>
>> If I however use the latter [SleeperThread::msleep()] approach inside a thread I see that the
>> function delay(1000) returns immediately.

When I try this, SleeperThread::msleep() does not return immediately,
neither when called from my main gui thread, nor when called in a separate
thread (called in the run() function of a QThread subclass).

So, either what isn't working for you works for me, which would be a puzzle,
or I didn't understand correctly what you tried to do and how it failed.

The reason I tried this, is that it seemed to me that what you tried should
have worked just as you expected (and it did, indeed, work for me).

Do we have an inconsistency in our test results, or did I misunderstand what
you were doing?

>> Did I understand something wrong? Which is the recommanded solution?
>> I know that in a thread I could as well use msleep, but I would like to
>> have a solution which can be used anywhere
>> in the programm and also outside of QThread classes.
>
> Why put the thread into a non-responsive state by sleeping or spinning in a
> loop? You can simply use a single shot timer to call a slot at after a
> specified delay whilst allowing the event loop to process events in the
> interim:
> ...

(As for the various suggestions about avoiding a delay, or using a timer
to produce a non-blocking delay, I agree.  My point in trying this was
because it looked to me that Matthias' scheme should work, not because
it's necessarily the cleanest way to meet his requirement.)


K. Frank




More information about the Qt-interest-old mailing list