OneThread.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "OneThread.h"
  2. #include <QDebug>
  3. #include <QCoreApplication>
  4. OneThread::OneThread(QThread* thread, QObject* parent) : QObject(parent), m_thread(thread)
  5. {
  6. /* 将自身移动到子线程中去 */
  7. this->moveToThread(m_thread);
  8. /* 指定为队列连接 */
  9. connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection);
  10. /* 注册数据类型 */
  11. qRegisterMetaType<std::function<int(void)>>("std::function<int(void)>");
  12. qRegisterMetaType<std::function<void(void)> >("std::function<void(void)>");
  13. /* 连接信号和槽 */
  14. connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask);
  15. connect(this, &OneThread::signal_runTaskRunOne, this, &OneThread::do_runTaskRunOne);
  16. }
  17. OneThread::OneThread(QObject* parent) : QObject(parent)
  18. {
  19. m_thread = new QThread();
  20. /* 将自身移动到子线程中去 */
  21. this->moveToThread(m_thread);
  22. /* 指定为队列连接 */
  23. connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection);
  24. /* 注册数据类型 */
  25. qRegisterMetaType<std::function<int(void)>>("std::function<int(void)>");
  26. qRegisterMetaType<std::function<void(void)> >("std::function<void(void)>");
  27. /* 连接信号和槽 */
  28. connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask);
  29. connect(this, &OneThread::signal_runTaskRunOne, this, &OneThread::do_runTaskRunOne);
  30. }
  31. OneThread::~OneThread()
  32. {
  33. if(m_thread != nullptr)
  34. {
  35. m_thread->quit();
  36. m_thread->wait();
  37. // delete m_thread;
  38. m_thread = nullptr;
  39. }
  40. }
  41. /* 传入函数,运行函数 */
  42. void OneThread::do_runTask(std::function<void(void)> func)
  43. {
  44. qDebug() << "----- do_runTask , Thread ID: " << QThread::currentThreadId();
  45. m_threadRunning = true;
  46. while(m_threadRunning)
  47. {
  48. func();
  49. /* 进入事件循环 */
  50. QCoreApplication::processEvents();
  51. /* 延时1ms */
  52. QThread::usleep(100);
  53. }
  54. qDebug() << "----- do_runTask end -----";
  55. }
  56. void OneThread::do_runTaskRunOne(std::function<void(void)> func)
  57. {
  58. func();
  59. }