FunctionTransfer.cpp 2.1 KB

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