Collection of DPF-based plugins for packaging
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.0KB

  1. //
  2. // Created by matthew on 1/11/19.
  3. //
  4. #ifndef PROJECTM_BELLEW_BACKGROUNDWORKER_H
  5. #define PROJECTM_BELLEW_BACKGROUNDWORKER_H
  6. // Small class to encapsulate synchronization of a simple background task runner
  7. // see projectM.cpp
  8. class BackgroundWorkerSync
  9. {
  10. pthread_mutex_t mutex;
  11. pthread_cond_t condition_start_work;
  12. pthread_cond_t condition_work_done;
  13. volatile bool there_is_work_to_do;
  14. volatile bool finished;
  15. public:
  16. BackgroundWorkerSync() : there_is_work_to_do(false), finished(false)
  17. {
  18. pthread_mutex_init(&mutex, NULL);
  19. pthread_cond_init(&condition_start_work, NULL);
  20. pthread_cond_init(&condition_work_done, NULL);
  21. }
  22. void reset()
  23. {
  24. there_is_work_to_do = false;
  25. finished = false;
  26. }
  27. // called by foreground
  28. void wake_up_bg()
  29. {
  30. pthread_mutex_lock(&mutex);
  31. there_is_work_to_do = true;
  32. pthread_cond_signal(&condition_start_work);
  33. pthread_mutex_unlock(&mutex);
  34. }
  35. // called by foreground
  36. void wait_for_bg_to_finish()
  37. {
  38. pthread_mutex_lock(&mutex);
  39. while (there_is_work_to_do)
  40. pthread_cond_wait(&condition_work_done, &mutex);
  41. pthread_mutex_unlock(&mutex);
  42. }
  43. // called by foreground() when shutting down, background thread should exit
  44. void finish_up()
  45. {
  46. pthread_mutex_lock(&mutex);
  47. finished = true;
  48. pthread_cond_signal(&condition_start_work);
  49. pthread_mutex_unlock(&mutex);
  50. }
  51. // called by background
  52. bool wait_for_work()
  53. {
  54. pthread_mutex_lock(&mutex);
  55. while (!there_is_work_to_do && !finished)
  56. pthread_cond_wait(&condition_start_work, &mutex);
  57. pthread_mutex_unlock(&mutex);
  58. return !finished;
  59. }
  60. // called by background
  61. void finished_work()
  62. {
  63. pthread_mutex_lock(&mutex);
  64. there_is_work_to_do = false;
  65. pthread_cond_signal(&condition_work_done);
  66. pthread_mutex_unlock(&mutex);
  67. }
  68. };
  69. #endif //PROJECTM_BELLEW_BACKGROUNDWORKER_H