内容表

上一话题

QTextStreamManipulator

下一话题

QThreadPool

QThread

QThread 类提供独立于平台的方式去管理线程。 更多

Inheritance diagram of PySide2.QtCore.QThread

概要

函数

虚函数

静态函数

详细描述

A QThread 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.

可以使用 Worker 对象,通过把它们移动到线程使用 moveToThread() .

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 QThread and reimplement run() 。例如:

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();
}
											

在该范例中,线程会在 run 函数有返回之后退出。没有任何事件循环会运行在线程中,除非调用 exec() .

It is important to remember that a QThread instance lives in 实例化它的旧线程,而不是新线程调用 run() . This means that all of QThread ‘s queued slots and invoked methods 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 QThread .

Unlike queued slots or invoked methods, methods called directly on the QThread object will execute in the thread that calls the method. When subclassing QThread , 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 Synchronizing Threads for details.

管理线程

QThread 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.

可以停止线程通过调用 exit() or quit() . In extreme cases, you may want to forcibly terminate() an executing thread. However, doing so is dangerous and discouraged. Please read the documentation for terminate() and setTerminationEnabled() for detailed information.

从 Qt 4.8 起,解除活在刚结束线程中的对象的分配是可能的,通过连接 finished() signal to deleteLater() .

使用 wait() to block the calling thread, until the other thread has finished execution (or until a specified time has passed).

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

注意

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

静态函数 currentThreadId() and currentThread() return identifiers for the currently executing thread. The former returns a platform specific ID for the thread; the latter returns a QThread 指针。

要选择给予线程的名称 (作为标识通过命令 ps -L 例如在 Linux),可以调用 setObjectName() before starting the thread. If you don’t call setObjectName() ,给予线程的名称将是线程对象 Runtime (运行时) 类型的类名 (例如: "RenderThread" 在案例 Mandelbrot 范例 , as that is the name of the QThread subclass). Note that this is currently not available with release builds on Windows.

class QThread ( [ parent=None ] )
param parent

QObject

构造新 QThread 去管理新线程。 parent 拥有所有权对于 QThread . The thread does not begin executing until start() 被调用。

另请参阅

start()

PySide2.QtCore.QThread. Priority

此枚举类型指示操作系统应如何调度新创建线程。

常量

描述

QThread.IdlePriority

才调度,当没有其它线程在运行时。

QThread.LowestPriority

调度更少经常比。

QThread.LowPriority

调度更少经常比。

QThread.NormalPriority

操作系统的默认优先级。

QThread.HighPriority

调度更多经常比。

QThread.HighestPriority

调度更多经常比。

QThread.TimeCriticalPriority

尽可能经常调度。

QThread.InheritPriority

使用如创建线程的相同优先级。这是默认。

static PySide2.QtCore.QThread. currentThread ( )
返回类型

QThread

返回指针指向 QThread 其管理目前正执行线程。

PySide2.QtCore.QThread. eventDispatcher ( )
返回类型

QAbstractEventDispatcher

返回指针指向线程的事件分派程序对象。若线程不存在事件分派程序,此函数返回 None .

PySide2.QtCore.QThread. exec_ ( )
返回类型

int

进入事件循环并等待,直到 exit() is called, returning the value that was passed to exit() . The value returned is 0 if exit() is called via quit() .

此函数意味着被调用从 run() . It is necessary to call this function to start event handling.

另请参阅

quit() exit()

PySide2.QtCore.QThread. exit ( [ retcode=0 ] )
参数

retcode int

Tells the thread’s event loop to exit with a return code.

在调用此函数之后,线程离开事件循环并返回从调用 exec() exec() function returns returnCode .

按约定, returnCode 0 意味着成功,任何非零值指示出错。

注意:不像同名 C 库函数,此函数 does return to the caller – it is event processing that stops.

没有 QEventLoop 会在此线程中被再次启动,直到 exec() has been called again. If the eventloop in exec() is not running then the next call to exec() will also return immediately.

static PySide2.QtCore.QThread. idealThreadCount ( )
返回类型

int

返回可以在系统中运行的理想线程数。这是通过查询系统中实际和逻辑处理器核心数来完成的。此函数返回 1,若无法检测处理器核心数。

PySide2.QtCore.QThread. isFinished ( )
返回类型

bool

返回 true 若线程已完成;否则返回 false .

另请参阅

isRunning()

PySide2.QtCore.QThread. isInterruptionRequested ( )
返回类型

bool

返回 true,若在此线程中正运行的任务应被停止。中断可以被请求通过 requestInterruption() .

此函数可以被用于使长时间运行的任务能完全中断。从不检查 (或处理) 由此函数返回的值是安全的,不管怎样,建议在长时间运行函数中定期这样做。当心不要太频繁调用它,以保持较低开销。

void long_task() {
     forever {
        if ( QThread::currentThread()->isInterruptionRequested() ) {
            return;
        }
    }
}
												
PySide2.QtCore.QThread. isRunning ( )
返回类型

bool

返回 true 若线程正在运行;否则返回 false .

另请参阅

isFinished()

PySide2.QtCore.QThread. loopLevel ( )
返回类型

int

返回线程的当前事件循环级别。

注意

这只可以在线程本身内被调用,即:当它是当前线程时。

static PySide2.QtCore.QThread. msleep ( arg__1 )
参数

arg__1 – long

强制当前线程休眠 msecs 毫秒。

避免使用此函数,若需要等待给定条件改变。相反,可把槽连接到指示改变的信号或使用事件处理程序 (见 event() ).

注意

此函数不保证准确性。应用程序可能休眠超过 msecs 在重负载条件下。某些 OS (操作系统) 可能圆整 msecs up to 10 ms or 15 ms.

PySide2.QtCore.QThread. priority ( )
返回类型

Priority

返回正运行线程的优先级。若线程未在运行,此函数返回 InheritPriority .

另请参阅

Priority setPriority() start()

PySide2.QtCore.QThread. quit ( )

Tells the thread’s event loop to exit with return code 0 (success). Equivalent to calling exit (0).

此函数什么都不做,若线程没有事件循环。

PySide2.QtCore.QThread. requestInterruption ( )

请求线程的中断。该请求是建议性的,且由在线程上运行的代码决定是否以及如何处理此请求。此函数不会停止在线程中运行的任何事件循环,也不会以任何方式终止它。

PySide2.QtCore.QThread. run ( )

线程的起点。先调用 start() , the newly created thread calls this function. The default implementation simply calls exec() .

可以重实现此函数以促进高级线程管理。来自此方法的返回将结束线程的执行。

另请参阅

start() wait()

PySide2.QtCore.QThread. setEventDispatcher ( eventDispatcher )
参数

eventDispatcher QAbstractEventDispatcher

把线程的事件分派程序设为 eventDispatcher 。这才是可能的,只要尚未为线程安装事件分派程序。也就是说,在线程被启动之前采用 start() or, in case of the main thread, before QCoreApplication 已被实例化。此方法获取对象的所有权。

另请参阅

eventDispatcher()

PySide2.QtCore.QThread. setPriority ( priority )
参数

priority Priority

此函数设置 priority 为正运行线程。若线程未在运行,此函数什么都不做并立即返回。使用 start() to start a thread with a specific priority.

priority 自变量可以是任意值在 QThread::Priority 枚举除了 InheritPriority .

作用为 priority parameter is dependent on the operating system’s scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler for more details).

另请参阅

Priority priority() start()

PySide2.QtCore.QThread. setStackSize ( stackSize )
参数

stackSize uint

把线程的最大堆栈尺寸设为 stackSize 。若 stackSize 大于 0,最大堆栈尺寸被设为 stackSize 字节,否则,最大堆栈尺寸由操作系统自动确定。

警告

大多数操作系统对线程堆栈尺寸,有最小和最大限制。线程将无法启动,若堆栈尺寸超出这些限制。

另请参阅

stackSize()

static PySide2.QtCore.QThread. setTerminationEnabled ( [ enabled=true ] )
参数

enabled bool

启用 (或禁用) 当前线程的终止,基于 enabled 参数。线程必须已被启动由 QThread .

enabled 为 false,终止被禁用。未来调用 terminate() will return immediately without effect. Instead, the termination is deferred until termination is enabled.

enabled 为 true,终止被启用。未来调用 terminate() will terminate the thread normally. If termination has been deferred (i.e. terminate() was called with termination disabled), this function will terminate the calling thread immediately 。注意:此函数不会返回,在此情况下。

另请参阅

terminate()

static PySide2.QtCore.QThread. sleep ( arg__1 )
参数

arg__1 – long

强制当前线程休眠 secs 秒。

避免使用此函数,若需要等待给定条件改变。相反,可把槽连接到指示改变的信号或使用事件处理程序 (见 event() ).

注意

此函数不保证准确性。应用程序可能休眠超过 secs 在重负载条件下。

PySide2.QtCore.QThread. stackSize ( )
返回类型

uint

返回线程的最大堆栈尺寸 (若设置采用 setStackSize() ); otherwise returns zero.

另请参阅

setStackSize()

PySide2.QtCore.QThread. start ( [ priority=InheritPriority ] )
参数

priority Priority

开始执行线程通过调用 run() . The operating system will schedule the thread according to the priority 参数。若线程已经在运行,此函数什么都不做。

作用为 priority parameter is dependent on the operating system’s scheduling policy. In particular, the priority 会被忽略,在不支持线程优先级的系统中 (如在 Linux,见 sched_setscheduler 文档编制了解更多细节)。

PySide2.QtCore.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 wait() after , to be sure.

当线程被终止时,等待线程完成的所有线程都将被唤醒。

警告

此函数是危险的,且不鼓励使用。线程可以在其代码路径中的任何点被终止。线程可以被终止,当修改数据时。线程没有机会在本身、解锁任何保持互斥、等之后被清理。简而言之,若绝对有必要才使用此函数。

终止可以被明确启用 (或禁用) 通过调用 setTerminationEnabled() . Calling this function while termination is disabled results in the termination being deferred, until termination is re-enabled. See the documentation of setTerminationEnabled() 了解更多信息。

static PySide2.QtCore.QThread. usleep ( arg__1 )
参数

arg__1 – long

强制当前线程休眠 usecs 微秒。

避免使用此函数,若需要等待给定条件改变。相反,可把槽连接到指示改变的信号或使用事件处理程序 (见 event() ).

注意

此函数不保证准确性。应用程序可能休眠超过 usecs 在重负载条件下。某些 OS (操作系统) 可能圆整 usecs 到 10 毫秒 (或 15 毫秒);在 Windows,它会被圆整到 1 毫秒的倍数。

PySide2.QtCore.QThread. wait ( [ deadline=QDeadlineTimer(QDeadlineTimer.Forever) ] )
参数

deadline QDeadlineTimer

返回类型

bool

阻塞线程,直到满足这些条件之一:

  • 关联此线程的 QThread 对象已执行完成 (即:当它返回从 run() ). This function will return true if the thread has finished. It also returns true if the thread has not been started yet.

  • deadline 到达。此函数将返回 false,若到达 deadline (最后期限)。

deadline (截止日期) 计时器设为 QDeadlineTimer::Forever (默认) 将从不超时:在此情况下,函数才返回当线程返回从 run() or if the thread has not yet started.

这提供的功能类似 POSIX pthread_join() 函数。

PySide2.QtCore.QThread. wait ( time )
参数

time – long

返回类型

bool

这是重载函数。

static PySide2.QtCore.QThread. yieldCurrentThread ( )

把当前线程的执行产生到另一可运行线程,若有的话。注意:操作系统决定切换到哪个线程。