On terça-feira, 19 de março de 2013 10.37.56, Hugo Drumond Jacob wrote:
> Hi folks!
>
> Today some doubt has ocurred on my office. Suppose that for some
> reason we need to sleep a thread (not the main thread) for some time

Suppose that you're wrong and you came to the wrong solution that sleeping is
the way to go. Try to find a solution that makes you do what you need to do and
not sleep.

> (eg. 100 ms). The QThread::wait(int) "provides similar functionality
> to the POSIX pthread_join()" and this don't will sleep the target
> thread, but the caller thread.
>
> Call the QThread::wait(int) from the target thread is forbidden
> (according to line 651 of qthread_unix.cpp).

You were looking for QThread::sleep, not wait. The latter is used to wait for
a thread to finish, with a given timeout. The former suspends and blocks
execution of the calling thread for a given time.

> Furthermore, is "wrong" call QThread::wait(int) except for
> synchronously thread termination with QThread::terminate() ? ( I know,
> isn't so healthy use QThread::terminate() ) QThread::wait(int) is a
> busy wait, right?

No, it isn't. It's like a pthread_join: it will suspend the execution of the
calling thread until the other thread exits or the timeout happens, whichever
comes first. QThread::wait() is normal use and is, in fact, used even by the
QThread destructor.

QThread::sleep() is, more often than not, a bad choice. Avoid it if you can.
If you can't, redesign your code so you don't need to use it.

> The attached code illustrate the question.

Your example has the main thread waiting for 100 ms for the auxiliary thread
to exit. But your auxiliary thread is busy-looping doing a qDebug and will
never exit. Since it doesn't exit, QThread::wait() will always timeout.

> My immediate solution is: create some MyThread class inherited of
> QThread just for expose the QThread::*sleep(unsigned long) methods and
> create some slot or Q_INVOKABLE method on Worker to call these exposed
> methods. Anyone propose some more elegant solution?

Yes: don't sleep.

--
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center

Attachment: signature.asc
Description: This is a digitally signed message part.

_______________________________________________
Interest mailing list
Interest@qt-project.org
http://lists.qt-project.org/mailman/listinfo/interest

Reply via email to