QThread workerThread = new QThread();
connect(workerThread, &QThread::finished, workerThread, &QObject::deleteLater);
注意:程序退出前,需要判断各线程是否已退出,如果不进行判断,很可能程序退出时会崩溃。如果线程的父对象是窗口对象,那么在窗体的析构函数中,还需要调用 wait() 等待线程完全结束再进行下面的析构。
大多数操作系统都为线程堆栈设置了最大和最小限制。如果超出这些限制,线程将无法启动。
每个线程都有自己的栈,彼此独立,由编译器分配。一般在 Windows 的栈大小为 2M,在 Linux 下是 8M。
Qt 提供了获取以及设置栈空间大小的函数:stackSize() 、setStackSize(uint stackSize)。其中 stackSize() 函数不是返回当前所在线程的栈大小,而是获取用 stackSize() 函数手动设置的栈大小。
没错,QThread 不再让线程间拼得你死我活,我们可以通过 setPriority() 设置线程优先级,通过 priority() 获取线程优先级。
| Constant | Value | Description |
|---|
| QThread::IdlePriority | 0 | scheduled only when no other threads are running. |
| QThread::LowestPriority | 1 | scheduled less often than LowPriority. |
| QThread::LowPriority | 2 | scheduled less often than NormalPriority. |
| QThread::NormalPriority | 3 | the default priority of the operating system. |
| QThread::HighPriority | 4 | scheduled more often than NormalPriority. |
| QThread::HighestPriority | 5 | scheduled more often than HighPriority. |
| QThread::TimeCriticalPriority | 6 | scheduled as often as possible. |
| QThread::InheritPriority | 7 | use the same priority as the creating thread. This is the default. |
此外,QThread 类还提供了 yieldCurrentThread() 静态函数,该函数是在通知操作系统“我这个线程不重要,优先处理其他线程吧”。当然,调用该函数后不会立马将 CPU 计算资源交出去,而是由操作系统决定。
QThread 类还提供了 sleep() 、msleep() 、usleep() 这三个函数,这三个函数也是在通知操作系统“在未来 time 时间内我不参与 CPU 计算”。
值得注意的是:usleep() 并 不能保证准确性 。某些OS可能将舍入时间设置为10us/15us;在 Windows 上它将四舍五入为 1ms 的倍数。