PDA

View Full Version : does main thread has sleep() ?



prasad_N
10th October 2015, 22:39
I know we can not put main thread in sleep, But I have tried for sleep method i did not find it & I found it in QThread only.
I can understand that as we should not put main thread in sleep that may be the reason we don't have sleep for main thread.
But is sleep() available to put main thread ideal for a while ?? // I struggled a lot to find sleep but could not

anda_skoa
10th October 2015, 23:03
The sleep() methods are public static.

Cheers,
_

prasad_N
11th October 2015, 13:07
The sleep() methods are public static.

Cheers,
_

No they are protected methods.

ars
11th October 2015, 13:20
They are public in Qt 5.x and protected in Qt 4.x. You could use something like the following:

class ThreadSleeper:public QThread
{
private:
ThreadSleeper(){};
virtual ~ThreadSleeper(){};
public:
using QThread::msleep;
};

...

ThreadSleeper::msleep(msec);


Best regards
ars

prasad_N
11th October 2015, 13:30
They are public in Qt 5.x and protected in Qt 4.x. You could use something like the following
ars

I wanted to sleep in main thread. Like below

Main()
{
///some standard code

sleep(1000);

}

And I am unsing Qt4.8

anda_skoa
11th October 2015, 13:43
I wanted to sleep in main thread.
And I am unsing Qt4.8

Given there are only 10 minutes between your comment and the answer by ars, I assume you have read it by now.

Cheers,
_

prasad_N
11th October 2015, 14:28
Could have tried it before replying. It worked.
Thanks.

ars
11th October 2015, 14:52
Sorry but can I use threadsleeper::msleep(m_sleep); to sleep main thread ?
You can use it to sleep any thread. More precisely, it sleeps the thread that calls this method. And as the main thread is a thread as any other thread, why shouldn't it be sent to sleep by calling this method? If you don't believe, just try this little code snippet:

#include <QCoreApplication>
#include <QThread>
#include <iostream>
#include <QTime>

class ThreadSleeper:public QThread
{
private:
ThreadSleeper(){};
virtual ~ThreadSleeper(){};

public:
using QThread::msleep;
};


int main(int , char *[])
{
std::cout << "sleeping for 5s" << std::endl;
QTime t;
t.start();
ThreadSleeper::msleep(5000);
std::cout << "slept for " << t.elapsed() << "ms" << std::endl;
}
Best regards
ars

@Prasad_N: I didn't see your previous reply before posting the above.