ActiveDispatcher.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. //
  2. // ActiveDispatcher.cpp
  3. //
  4. // $Id: //poco/1.4/Foundation/src/ActiveDispatcher.cpp#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Threading
  8. // Module: ActiveObjects
  9. //
  10. // Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #include "Poco/ActiveDispatcher.h"
  16. #include "Poco/Notification.h"
  17. #include "Poco/AutoPtr.h"
  18. namespace Poco {
  19. namespace
  20. {
  21. class MethodNotification: public Notification
  22. {
  23. public:
  24. MethodNotification(ActiveRunnableBase::Ptr pRunnable):
  25. _pRunnable(pRunnable)
  26. {
  27. }
  28. ActiveRunnableBase::Ptr runnable() const
  29. {
  30. return _pRunnable;
  31. }
  32. private:
  33. ActiveRunnableBase::Ptr _pRunnable;
  34. };
  35. class StopNotification: public Notification
  36. {
  37. };
  38. }
  39. ActiveDispatcher::ActiveDispatcher()
  40. {
  41. _thread.start(*this);
  42. }
  43. ActiveDispatcher::ActiveDispatcher(Thread::Priority prio)
  44. {
  45. _thread.setPriority(prio);
  46. _thread.start(*this);
  47. }
  48. ActiveDispatcher::~ActiveDispatcher()
  49. {
  50. try
  51. {
  52. stop();
  53. }
  54. catch (...)
  55. {
  56. }
  57. }
  58. void ActiveDispatcher::start(ActiveRunnableBase::Ptr pRunnable)
  59. {
  60. poco_check_ptr (pRunnable);
  61. _queue.enqueueNotification(new MethodNotification(pRunnable));
  62. }
  63. void ActiveDispatcher::cancel()
  64. {
  65. _queue.clear();
  66. }
  67. void ActiveDispatcher::run()
  68. {
  69. AutoPtr<Notification> pNf = _queue.waitDequeueNotification();
  70. while (pNf && !dynamic_cast<StopNotification*>(pNf.get()))
  71. {
  72. MethodNotification* pMethodNf = dynamic_cast<MethodNotification*>(pNf.get());
  73. poco_check_ptr (pMethodNf);
  74. ActiveRunnableBase::Ptr pRunnable = pMethodNf->runnable();
  75. pRunnable->duplicate(); // run will release
  76. pRunnable->run();
  77. pNf = _queue.waitDequeueNotification();
  78. }
  79. }
  80. void ActiveDispatcher::stop()
  81. {
  82. _queue.clear();
  83. _queue.wakeUpAll();
  84. _queue.enqueueNotification(new StopNotification);
  85. _thread.join();
  86. }
  87. } // namespace Poco