ThreadableJob.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * ThreadableJob.h - declaration of class ThreadableJob
  3. *
  4. * Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  5. *
  6. * This file is part of LMMS - https://lmms.io
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public
  19. * License along with this program (see COPYING); if not, write to the
  20. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301 USA.
  22. *
  23. */
  24. #ifndef THREADABLE_JOB_H
  25. #define THREADABLE_JOB_H
  26. #include "lmms_basics.h"
  27. #include <atomic>
  28. class ThreadableJob
  29. {
  30. public:
  31. enum class ProcessingState : int
  32. {
  33. Unstarted,
  34. Queued,
  35. InProgress,
  36. Done
  37. };
  38. ThreadableJob() :
  39. m_state(ProcessingState::Unstarted)
  40. {
  41. }
  42. inline ProcessingState state() const
  43. {
  44. return m_state.load();
  45. }
  46. inline void reset()
  47. {
  48. m_state = ProcessingState::Unstarted;
  49. }
  50. inline void queue()
  51. {
  52. m_state = ProcessingState::Queued;
  53. }
  54. inline void done()
  55. {
  56. m_state = ProcessingState::Done;
  57. }
  58. void process()
  59. {
  60. auto expected = ProcessingState::Queued;
  61. if (m_state.compare_exchange_strong(expected, ProcessingState::InProgress))
  62. {
  63. doProcessing();
  64. m_state = ProcessingState::Done;
  65. }
  66. }
  67. virtual bool requiresProcessing() const = 0;
  68. protected:
  69. virtual void doProcessing() = 0;
  70. std::atomic<ProcessingState> m_state;
  71. } ;
  72. #endif