IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

QThread Class

The https:// class provides a platform-independent way to manage threads.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

QThread Class▲

  • Header: QThread

  • qmake: QT += core

  • Inherited By:

  • Group: QThread is part of thread

Detailed Description▲

A https:// object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.

You can use worker objects by moving them to the thread using QObject::moveToThread().

 
Sélectionnez
class Worker : public QObject
{
    Q_OBJECT

public slots:
    void doWork(const QString &parameter) {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }

signals:
    void resultReady(const QString &result);
};

class Controller : public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
        connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
        connect(this, &Controller::operate, worker, &Worker::doWork);
        connect(worker, &Worker::resultReady, this, &Controller::handleResults);
        workerThread.start();
    }
    ~Controller() {
        workerThread.quit();
        workerThread.wait();
    }
public slots:
    void handleResults(const QString &);
signals:
    void operate(const QString &);
};

The code inside the Worker's slot would then execute in a separate thread. However, you are free to connect the Worker's slots to any signal, from any object, in any thread. It is safe to connect signals and slots across different threads, thanks to a mechanism called queued connections.

Another way to make code run in a separate thread, is to subclass https:// and reimplement run(). For example:

 
Sélectionnez
class WorkerThread : public QThread
{
    Q_OBJECT
    void run() override {
        QString result;
        /* ... here is the expensive or blocking operation ... */
        emit resultReady(result);
    }
signals:
    void resultReady(const QString &s);
};

void MyObject::startWorkInAThread()
{
    WorkerThread *workerThread = new WorkerThread(this);
    connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
    connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
    workerThread->start();
}

In that example, the thread will exit after the run function has returned. There will not be any event loop running in the thread unless you call exec().

It is important to remember that a https:// instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of https://'s queued slots and https:// will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed https://.

Unlike queued slots or invoked methods, methods called directly on the https:// object will execute in the thread that calls the method. When subclassing https://, keep in mind that the constructor executes in the old thread while run() executes in the new thread. If a member variable is accessed from both functions, then the variable is accessed from two different threads. Check that it is safe to do so.

Care must be taken when interacting with objects across different threads. See https:// for details.

Managing Threads▲

https:// will notifiy you via a signal when the thread is started() and finished(), or you can use isFinished() and isRunning() to query the state of the thread.

You can stop the thread by calling exit() or quit(). In extreme cases, you may want to forcibly https://() an executing thread. However, doing so is dangerous and discouraged. Please read the documentation for https://() and https://() for detailed information.

From Qt 4.8 onwards, it is possible to deallocate objects that live in a thread that has just ended, by connecting the finished() signal to QObject::deleteLater().

Use https://() to block the calling thread, until the other thread has finished execution (or until a specified time has passed).

https:// also provides static, platform independent sleep functions: https://(), https://(), and https://() allow full second, millisecond, and microsecond resolution respectively. These functions were made public in Qt 5.0.

https://() and the https://() functions should be unnecessary in general, since Qt is an event-driven framework. Instead of https://(), consider listening for the finished() signal. Instead of the https://() functions, consider using QTimer.

The static functions currentThreadId() and currentThread() return identifiers for the currently executing thread. The former returns a platform specific ID for the thread; the latter returns a https:// pointer.

To choose the name that your thread will be given (as identified by the command ps -L on Linux, for example), you can call setObjectName() before starting the thread. If you don't call https://, the name given to your thread will be the class name of the runtime type of your thread object (for example, "RenderThread" in the case of the Mandelbrot Example, as that is the name of the https:// subclass). Note that this is currently not available with release builds on Windows.

See Also▲

See also https://, https://, https://, https://, https://, https://

Member Function Documentation▲

 

[static] void QThread::msleep(unsigned long msecs)▲

Forces the current thread to sleep for msecs milliseconds.

Avoid using this function if you need to wait for a given condition to change. Instead, connect a slot to the signal that indicates the change or use an event handler (see QObject::event()).

This function does not guarantee accuracy. The application may sleep longer than msecs under heavy load conditions. Some OSes might round msecs up to 10 ms or 15 ms.

See Also▲

See also https://(), https://()

[static protected] void QThread::setTerminationEnabled(bool enabled = true)▲

Enables or disables termination of the current thread based on the enabled parameter. The thread must have been started by https://.

When enabled is false, termination is disabled. Future calls to https://() will return immediately without effect. Instead, the termination is deferred until termination is enabled.

When enabled is true, termination is enabled. Future calls to https://() will terminate the thread normally. If termination has been deferred (i.e. https://() was called with termination disabled), this function will terminate the calling thread immediately. Note that this function will not return in this case.

See Also▲

See also https://()

[static] void QThread::sleep(unsigned long secs)▲

Forces the current thread to sleep for secs seconds.

Avoid using this function if you need to wait for a given condition to change. Instead, connect a slot to the signal that indicates the change or use an event handler (see QObject::event()).

This function does not guarantee accuracy. The application may sleep longer than secs under heavy load conditions.

See Also▲

See also https://(), https://()

void QThread::terminate()▲

Terminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating system's scheduling policies. Use https://() after terminate(), to be sure.

When the thread is terminated, all threads waiting for the thread to finish will be woken up.

This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

Termination can be explicitly enabled or disabled by calling https://(). Calling this function while termination is disabled results in the termination being deferred, until termination is re-enabled. See the documentation of https://() for more information.

See Also▲

See also https://()

[static] void QThread::usleep(unsigned long usecs)▲

Forces the current thread to sleep for usecs microseconds.

Avoid using this function if you need to wait for a given condition to change. Instead, connect a slot to the signal that indicates the change or use an event handler (see QObject::event()).

This function does not guarantee accuracy. The application may sleep longer than usecs under heavy load conditions. Some OSes might round usecs up to 10 ms or 15 ms; on Windows, it will be rounded up to a multiple of 1 ms.

See Also▲

See also https://(), https://()

bool QThread::wait(unsigned long time = ULONG_MAX)▲

Blocks the thread until either of these conditions is met:

  • The thread associated with this https:// object has finished execution (i.e. when it returns from run()). This function will return true if the thread has finished. It also returns true if the thread has not been started yet.

  • time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the thread must return from run()). This function will return false if the wait timed out.

This provides similar functionality to the POSIX pthread_join() function.

See Also▲

See also https://(), https://()

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+   

Ce document est disponible sous la licence https:// telle que publiée par la Free Software Foundation.