• 1633阅读
  • 5回复

[提问]子线程启动、关闭、再启动的问题 [复制链接]

上一主题 下一主题
在线weiweiqiao
 

只看楼主 倒序阅读 楼主  发表于: 2021-06-07

我在读取数据时,希望在子线程中读取,不要影响到ui用户体验,当读取完数据后,将子线程关闭,减少资源消耗。
现有代码如下,希望大佬指点。
启动子线程:
  1. void Ui_process::start_sub_thread(QThread &thread, QObject *process)
  2. {
  3.     if ( !thread.isRunning()) {
  4.         if (nullptr != process) {
  5.             // Move object into sub thread. create signal/slot
  6.             process->moveToThread(&thread);
  7. //            connect(&thread, &QThread::finished, process, &QObject::deleteLater);
  8.             thread.start();
  9.         }
  10.     }
  11. }
当子线程处理完数据,将处理对象移出子线程:
  1. void Ui_process::sl_quit_sub_thread(int index)
  2. {
  3.        if ( file_thread_.isRunning()) {
  4.             qDebug()<< file_thread_.currentThreadId() << endl;
  5.             file_thread_.quit();
  6.             file_process_->moveToThread(this->thread()->currentThread());
  7. //            file_process_->setParent(nullptr);
  8.             disconnect(&file_thread_, nullptr, file_process_, nullptr);
  9.             qDebug()<< QThread::currentThreadId() << endl;
  10.         }
  11. }
我的程序运行结果正常,如下图所示:
  1. main thread 0x1314
  2. [NSE]KVirtualFolder::Initialize(5180),AssociationItemIcon(H:\)
  3. file_thread 0x718
  4. 0x1314
  5. QObject::moveToThread: Current thread (0x4863f0) is not the object's thread (0x4b5c78).
  6. Cannot move to target thread (0x4863f0)
  7. 0x1314
  8. file_thread 0x27dc
  9. 0x1314
  10. QObject::moveToThread: Current thread (0x4863f0) is not the object's thread (0x4b5c78).
  11. Cannot move to target thread (0x4863f0)
  12. 0x1314
  13. 18:28:46: H:\code\QtCode\my_examples\build-TrackDataAnalysor-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug\debug\TrackDataAnalysor.exe exited with code 0
主线程:main thread 0x1314

子线程:file_thread 0x718
但是后面“QObject::moveToThread: Current thread (0x4863f0) is not the object's thread (0x4b5c78).”中的线程id,不知道是从哪里来的。而且程序退出时正常返回0,有谁能给解释下么?
Jobs Insanely Great.
离线yuyu414

只看该作者 1楼 发表于: 2021-06-08
Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread. There is one exception to this rule however: objects with no thread affinity can be "pulled" to the current thread.
离线yuyu414

只看该作者 2楼 发表于: 2021-06-08
没有必要,线程空跑并不会占用资源,你的需求用QThreadPool更合适
在线weiweiqiao

只看该作者 3楼 发表于: 2021-06-09
回 yuyu414 的帖子
yuyu414:没有必要,线程空跑并不会占用资源,你的需求用QThreadPool更合适 (2021-06-08 16:40) 

好的,谢谢,我试试
Jobs Insanely Great.
离线九重水

只看该作者 4楼 发表于: 2021-06-10
我的子线程好像没关过,都是在等‘事务’进来,有就处理,没就干等着。
1条评分金钱+10
20091001753 金钱 +10 勤俭节约,闲时析构 2021-06-12
在线weiweiqiao

只看该作者 5楼 发表于: 2021-06-10
回 九重水 的帖子
九重水:我的子线程好像没关过,都是在等‘事务’进来,有就处理,没就干等着。[表情]  (2021-06-10 09:55) 

哈哈,我原来也是放着不管,现在想试试看多次启动有啥情况~
1条评分金钱+10
20091001753 金钱 +10 勤俭节约,闲时析构 2021-06-12
Jobs Insanely Great.
快速回复
限100 字节
 
上一个 下一个