FunctionTransfer.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "FunctionTransfer.h"
  2. #include <QThread>
  3. #include <QDebug>
  4. Qt::HANDLE FunctionTransfer::gMainThreadId = nullptr;
  5. FunctionTransfer *FunctionTransfer::main_thread_forward = nullptr;
  6. Q_DECLARE_METATYPE(std::function<void()>)
  7. FunctionTransfer::FunctionTransfer(QObject *parent) :
  8. QObject(parent)
  9. {
  10. //因为std::function<void()>是自定义的类型 要跨线程传递需要先注册一下
  11. qRegisterMetaType<std::function<void()>>();
  12. connect(this, SIGNAL(comming(std::function<void()>)), this, SLOT(slotExec(std::function<void()>)), Qt::BlockingQueuedConnection);
  13. connect(this, SIGNAL(comming_noBlock(std::function<void()>)), this, SLOT(slotExec(std::function<void()>)), Qt::QueuedConnection);
  14. }
  15. FunctionTransfer::~FunctionTransfer()
  16. {
  17. }
  18. void FunctionTransfer::init(Qt::HANDLE id)
  19. {
  20. gMainThreadId = id;
  21. FunctionTransfer::main_thread_forward = new FunctionTransfer();
  22. }
  23. bool FunctionTransfer::isMainThread()
  24. {
  25. if (gMainThreadId == nullptr)
  26. {
  27. qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<"the main thread id is not set!";
  28. return false;
  29. }
  30. if (QThread::currentThreadId() == gMainThreadId)
  31. {
  32. return true;
  33. }
  34. else
  35. {
  36. return false;
  37. }
  38. }
  39. void FunctionTransfer::runInMainThread(std::function<void()> f, bool isBlock)
  40. {
  41. // FunctionTransfer::main_thread_forward->exec(f, isBlock);
  42. if(FunctionTransfer::isMainThread())
  43. {
  44. f();
  45. }
  46. else
  47. {
  48. if (isBlock)
  49. {
  50. Q_EMIT FunctionTransfer::main_thread_forward->comming(f);
  51. }
  52. else
  53. {
  54. Q_EMIT FunctionTransfer::main_thread_forward->comming_noBlock(f);
  55. }
  56. }
  57. }
  58. void FunctionTransfer::slotExec(std::function<void()> f)
  59. {
  60. f();
  61. // if(FunctionTransfer::isMainThread())
  62. // {
  63. // f();
  64. // }
  65. // else
  66. // {
  67. // if (isBlock)
  68. // {
  69. // Q_EMIT this->comming(f);
  70. // }
  71. // else
  72. // {
  73. // Q_EMIT this->comming_noBlock(f);
  74. // }
  75. // }
  76. }