在qt中使用了多线程,有些事项是需要额外注意的:
Qt中提供一个线程类,通过这个类就可以创建子线程了,Qt中一共提供了两种创建子线程的方式。这个类的常用API函数:
| public函数 | |
| QThread(QObject *parent = nullptr) | 构造函数 |
| virtual ~QThread() | 析构函数 |
| QAbstractEventDispatcher * eventDispatcher() const | |
| bool isFinished() const | 判断线程中的任务是不是处理完毕了 |
| bool isInterruptionRequested() const | |
| bool isRunning() const | 判断子线程是不是在执行任务 |
| int loopLevel() const | |
| QThread::Priority priority() const | 得到当前线程的优先级 |
| void requestInterruption() | |
| void setEventDispatcher(QAbstractEventDispatcher *eventDispatcher) | |
| void setPriority(QThread::Priority priority) | 设置线程优先级 |
| void setStackSize(uint stackSize) | |
| uint stackSize() const | |
| bool wait(QDeadlineTimer deadline = QDeadlineTimer(QDeadlineTimer::Forever)) | |
| bool wait(unsigned long time) | 等待任务完成,然后退出线程,一般情况会在exit()后边调用这个函数 |
| 槽函数 | |
| void exit(int returnCode = 0) | 退出线程,停止底层的事件循环 |
| void quit() | 和调用exit()效果是一样的,使用这个函数后,再调用wait()函数 |
| void start(QThread::Priority priority = InheritPriority) | 启动子线程 |
| void terminate() | 线程退出,可能是会马上终止线程,一般情况下不使用这个函数 |
| 信号函数 | |
| void finished() | 线程中执行的任务完成了发出该信号,,任务函数中的处理逻辑执行完毕 |
| void started() | 开始工作之前发出这个信号,一般不使用 |
| 静态公共成员 | |
| QThread * create(Function &&f, Args &&... args) | |
| QThread * currentThread() | 返回一个指向管理当前执行线程的QThread的指针 |
| Qt::HANDLE currentThreadId() | |
| int idealThreadCount() | 返回可以在系统上运行的理想线程数 == 当前电脑的CPU核心数相同 |
| void msleep(unsigned long msecs) | 线程休眠函数 毫秒 |
| void sleep(unsigned long secs) | 线程休眠函数 秒 |
| void usleep(unsigned long usecs) | 线程休眠函数 微秒 |
| void yieldCurrentThread() | |
| 受保护的函数 | |
| int exec() | |
| virtual void run() | 子线程要处理什么任务,需要写到run()中 |
QT中提供的多线程的第一种使用方式的特点是:简单。操作步骤如下:1. 需要创建一个线程的子类,让其继承QT中的线程类QThread,比如:
- class MyThread : public QThread
- {
- ...
- }
- class MyThread : public QThread
- {
- ... ...
- protected:
- void run()
- {
- ... ...
- }
-
- }
MyThread* subThread = new MyThread;
subThread->start();
不能在类的外部调用run()方法启动子线程,在外部调用start()相当于让run()开始运行,当子线程创建出来后,父子线程之间的通信可以通过信号槽的方式,注意事项:
Qt提供的第二种线程的创建方式弥补了第一种的缺点,用起来更加灵活,但是这种方式写起来会相对复杂一些,其具体操作步骤如下:
- class MyWork : public QObject
- {
- ... ...
- }
- class MyWork : public QObject
- {
- public:
- ... ...
-
- //函数名自己指定,叫什么都可以,参数可以根据实际需求添加
- void working();
-
- }
QThread* sub = new QThread;
MyWork* work = new MyWork;
- //移动到子线程中工作
- work->moveToThread(sub);