OneThread.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "OneThread.h"
  2. #include <QDebug>
  3. OneThread::OneThread(QThread* thread, QObject* parent) : QObject(parent), m_thread(thread)
  4. {
  5. m_timerStartThread.setTimerType(Qt::PreciseTimer);
  6. m_timerStartThread.setSingleShot(true);
  7. /* 将自身移动到子线程中去 */
  8. this->moveToThread(m_thread);
  9. /* 连接信号和槽 */
  10. connect(&m_timerStartThread, &QTimer::timeout, this, &OneThread::do_timeoutWork);
  11. connect(this, &OneThread::signal_startThread, this, &OneThread::do_timeoutWork);
  12. /* 指定为队列连接 */
  13. connect(this, &OneThread::signal_runTask, this, &OneThread::do_runTask,Qt::QueuedConnection);
  14. /* 注册数据类型 */
  15. qRegisterMetaType<std::function<int(void)>>("std::function<int(void)>");
  16. qRegisterMetaType<std::function<void(void)> >("std::function<void(void)>");
  17. }
  18. OneThread::~OneThread()
  19. {
  20. if(m_thread != nullptr)
  21. {
  22. m_thread->quit();
  23. m_thread->wait();
  24. // delete m_thread;
  25. m_thread = nullptr;
  26. }
  27. }
  28. /* 开启线程 */
  29. void OneThread::startThread()
  30. {
  31. m_timerStartThread.start(0);
  32. }
  33. /* 线程函数 */
  34. void OneThread::do_timeoutWork()
  35. {
  36. qDebug() << "----- do_timeoutWork , Thread ID: " << QThread::currentThreadId();
  37. // emit signal_runTask(m_func);
  38. qDebug() << "----- do_timeoutWork end -----";
  39. }
  40. /* 传入函数,运行函数 */
  41. void OneThread::do_runTask(std::function<void(void)> func)
  42. {
  43. qDebug() << "----- do_runTask , Thread ID: " << QThread::currentThreadId();
  44. func();
  45. qDebug() << "----- do_runTask end -----";
  46. }