The QThread class provides a platform-independent way to manage threads. 更多...
继承 QObject .
The QThread class provides a platform-independent way to manage threads.
A QThread object manages one thread of control within the program. QThreads begin executing in run ()。默认情况下, run () 启动事件循环通过调用 exec_ () and runs a Qt event loop inside the thread.
可以使用 Worker 对象,通过把它们移动到线程使用 QObject.moveToThread ().
class Worker : public QObject { Q_OBJECT QThread workerThread; public slots: void doWork(const QString ¶meter) { // ... 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, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(this, SIGNAL(operate(QString)), worker, SLOT(doWork(QString))); connect(worker, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString))); 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() { QString result; /* expensive or blocking operation */ emit resultReady(result); } signals: void resultReady(const QString &s); }; void MyObject.startWorkInAThread() { WorkerThread *workerThread = new WorkerThread(this); connect(workerThread, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString))); connect(workerThread, SIGNAL(finished()), workerThread, SLOT(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_ ().
重点记住,QThread 实例 活在 the old thread that instantiated it, not in the new thread that calls run (). This means that all of QThread's queued slots 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.
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 同步线程 for details.
QThread 将凭借信号通知您当线程 started (), finished (),和 terminated (),或可以使用 isFinished () 和 isRunning () to query the state of the thread.
可以停止线程通过调用 exit () 或 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 () 和 setTerminationEnabled () 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 () 信号到 QObject.deleteLater ().
使用 wait () to block the calling thread, until the other thread has finished execution (or until a specified time has passed).
静态函数 currentThreadId () 和 currentThread () return identifiers for the currently executing thread. The former returns a platform specific ID for the thread; the latter returns a QThread pointer.
To choose the name that your thread will be given (as identified by the command ps -L 例如在 Linux),可以调用 setObjectName() before starting the thread. If you don't call setObjectName() , 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 范例 , as that is the name of the QThread subclass). Note that this is currently not available with release builds on Windows.
QThread also provides static, platform independent sleep functions: sleep (), msleep (),和 usleep () allow full second, millisecond, and microsecond resolution respectively.
注意: 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 .
{Mandelbrot Example}, {Semaphores Example}, {Wait Conditions Example}
This enum type indicates how the operating system should schedule newly created threads.
| 常量 | 值 | 描述 |
|---|---|---|
| QThread.IdlePriority | 0 | scheduled only when no other threads are running. |
| QThread.LowestPriority | 1 | 经常比 LowPriority 更少调度。 |
| QThread.LowPriority | 2 | 经常比 NormalPriority 更少调度。 |
| QThread.NormalPriority | 3 | the default priority of the operating system. |
| QThread.HighPriority | 4 | 经常比 NormalPriority 更多调度。 |
| QThread.HighestPriority | 5 | 经常比 HighPriority 更多调度。 |
| QThread.TimeCriticalPriority | 6 | 尽可能经常调度。 |
| QThread.InheritPriority | 7 | use the same priority as the creating thread. This is the default. |
parent argument, if not None, causes self to be owned by Qt instead of PyQt.
构造新 QThread to manage a new thread. The parent 拥有所有权对于 QThread . The thread does not begin executing until start () 被调用。
另请参阅 start ().
返回指针指向 QThread which manages the currently executing thread.
返回目前执行线程的线程句柄。
警告: The handle returned by this function is used for internal purposes and should not be used in any application 代码。
警告: 在 Windows,返回值是 pseudo-handle for the current thread. It can't be used for numerical comparison. i.e., this function returns the DWORD (Windows-Thread ID) returned by the Win32 function getCurrentThreadId(), not the HANDLE (Windows-Thread HANDLE) returned by the Win32 function getCurrentThread().
进入事件循环并等待,直到 exit () is called, returning the value that was passed to exit (). The value returned is 0 if exit () is called 凭借 quit ().
此函数意味着被调用从 run (). It is necessary to call this function to start event handling.
告诉线程的事件循环采用返回代码退出。
After calling this function, the thread leaves the event loop and returns from the call to QEventLoop.exec ()。 QEventLoop.exec () 函数返回 returnCode .
按约定, returnCode of 0 means success, any non-zero value indicates an error.
Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.
没有 QEventLoop 会在此线程中被再次启动,直到 QThread.exec () has been called again. If the eventloop in QThread.exec () is not running then the next call to QThread.exec () will also return immediately.
另请参阅 quit () 和 QEventLoop .
Returns the ideal number of threads that can be run on the system. This is done querying the number of processor cores, both real and logical, in the system. This function returns -1 if the number of processor cores could not be detected.
Returns true if the thread is finished; otherwise returns false.
另请参阅 isRunning ().
Returns true if the thread is running; otherwise returns false.
另请参阅 isFinished ().
强制当前线程休眠 msecs 毫秒。
Returns the priority for a running thread. If the thread is not running, this function returns InheritPriority .
该函数在 Qt 4.1 引入。
另请参阅 Priority , setPriority (),和 start ().
This method is also a Qt slot with the C++ signature void quit() .
Tells the thread's event loop to exit with return code 0 (success). Equivalent to calling QThread.exit(0).
This function does nothing if the thread does not have an event loop.
另请参阅 exit () 和 QEventLoop .
线程的起点。先调用 start (), the newly created thread calls this function. The default implementation simply calls exec_ ().
You can reimplement this function to facilitate advanced thread management. Returning from this method will end the execution of the thread.
此函数设置 priority for a running thread. If the thread is not running, this function does nothing and returns immediately. Use start () to start a thread with a specific priority.
priority 自变量可以是任意值在 QThread.Priority 枚举除了 InheritPriorty .
作用为 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).
该函数在 Qt 4.1 引入。
另请参阅 Priority , priority (),和 start ().
把线程的最大堆栈尺寸设为 stackSize . 若 stackSize is greater than zero, the maximum stack size is 设为 stackSize bytes, otherwise the maximum stack size is automatically determined by the operating system.
警告: Most operating systems place minimum and maximum limits on thread stack sizes. The thread will fail to start if the stack size is outside these limits.
另请参阅 stackSize ().
Enables or disables termination of the current thread based on the enabled 参数。线程必须已被启动由 QThread .
When enabled is false, termination is disabled. Future calls to QThread.terminate () will return immediately without effect. Instead, the termination is deferred until termination is enabled.
When enabled is true, termination is enabled. Future calls to QThread.terminate () will terminate the thread normally. If termination has been deferred (i.e. QThread.terminate () was called with termination disabled), this function will terminate the calling thread immediately . Note that this function will not return in this case.
另请参阅 terminate ().
强制当前线程休眠 secs 秒。
返回线程的最大堆栈尺寸 (若设置采用 setStackSize ()); otherwise returns zero.
另请参阅 setStackSize ().
This method is also a Qt slot with the C++ signature void start(QThread::Priority = QThread.InheritPriority) .
开始执行线程通过调用 run (). The operating system will schedule the thread according to the priority parameter. If the thread is already running, this function does nothing.
作用为 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).
This method is also a Qt slot with the C++ signature void terminate() .
Terminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating system's scheduling policies. Listen for the terminated () signal, or use QThread.wait () 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.
终止可以被明确启用 (或禁用) 通过调用 QThread.setTerminationEnabled (). Calling this function while termination is disabled results in the termination being deferred, until termination is re-enabled. See the documentation of QThread.setTerminationEnabled () 了解更多信息。
另请参阅 setTerminationEnabled ().
强制当前线程休眠 usecs 微秒。
阻塞线程,直到满足这些条件之一:
这提供的功能类似 POSIX pthread_join() 函数。
Yields execution of the current thread to another runnable thread, if any. Note that the operating system decides to which thread to switch.
This is the default overload of this signal.
This signal is emitted when the thread has finished executing.
另请参阅 started () 和 terminated ().
This is the default overload of this signal.
This signal is emitted when the thread starts executing.
另请参阅 finished () and terminated ().
This is the default overload of this signal.
This signal is emitted when the thread is terminated.