Start thread 0 at 31:05.66 Start thread 2 at 31:05.66 Start thread 1 at 31:05.66 deconstruct Task with ID 2 deconstruct Task with ID 0 Start thread 3 at 31:06.703 deconstruct Task with ID 1 Start thread 4 at 31:06.704 Start thread 5 at 31:06.704 deconstruct Task with ID 3 Start thread 6 at 31:08.173 deconstruct Task with ID 5 Start thread 7 at 31:08.173 deconstruct Task with ID 4 Start thread 8 at 31:08.173 deconstruct Task with ID 6 Start thread 9 at 31:09.507 deconstruct Task with ID 8 Start thread 10 at 31:09.508 deconstruct Task with ID 7 Start thread 11 at 31:09.508 deconstruct Task with ID 9 Start thread 12 at 31:11.009 deconstruct Task with ID 10 Start thread 13 at 31:11.009 deconstruct Task with ID 11 Start thread 14 at 31:11.01 deconstruct Task with ID 14 deconstruct Task with ID 13 deconstruct Task with ID 12
程序当中QRunnable是以指针的形式创建的,是QThreadPool在运行完线程后自动释放,官方文档有一句:QThreadPool takes ownership and deletes QRunnable object automatically,这也是Qt半自动内存回收机制的一方面。
然后在GUI线程的构造函数里创建MyThread对象,运行线程后会报错: QObject: Cannot create children for a parent that is in a different thread.
(Parent is MyThread(0x2d07e70), parent's thread is QThread(0x2cea418)
也就是说MyThread对象在GUI线程,而obj在子线程。
moveToThread底层是依赖Qt事件循环实现的(QCoreApplication::postEvent),所以使用moveToThread必须是在开启Qt事件循环的程序中,就是main函数中调用QCoreApplication::exec的程序。
自定义QObject的子类MyObj,注意不能是QWidget的子类,因为它不可重入: