在项目中碰到了一个问题,如果初始化一个线程,这个线程不执行完毕的话,那么再次调用其余线程则不会执行。猜想其可能被阻塞,后来查找了一些资料发现原因如下。
这是我开启线程的方式:
CustomRunnable* runnable = new CustomRunnable();
runnable->setCallbackFunction(SerialPortReadThread, this);
QThreadPool::globalInstance()->start(runnable);
其中CustomRunnable继承了QRunnable,QThreadPool::globalInstance()用于获取QT中的全局QThreadPool对象,SerialPortReadThread是我需要执行的函数,用于阻塞读取串口中的数据并处理,如果先执行了这些,那么接下来的线程都不会被执行.
查找资料得可能是在ARM上面跑的原因,线程最大个数默认为1,这个和处理器有关系.通过QThreadPool::globalInstance()->maxThreadCount()可查看当前环境最大线程数,那么显然就找到了原因,SerialPortReadThread是一个死循环,唯一线程资源永远被占用,后面执行的线程都不会被执行了.
通过设置线程最大个数可以解决这个问题:QThreadPool::globalInstance()->setMaxThreadCount(2);我在这里将他设置为2
qWarning() << QThreadPool::globalInstance()->maxThreadCount() << "maxThreadCount";
//set MaxThreadCount
QThreadPool::globalInstance()->setMaxThreadCount(2);
qWarning() << QThreadPool::globalInstance()->maxThreadCount() << "maxThreadCount";
打印如下:
Warning: 1 maxThreadCount
Warning: 2 maxThreadCount
问题解决.
因为一直觉得线程个数是无限多的,所以犯了这个错误,留个笔记,以后不要再犯,