Thread.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (C) 2016 Intel Corporation. All rights reserved.
  3. *
  4. * This file is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the
  6. * Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This file is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. * See the GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License along
  15. * with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #pragma once
  18. #include <pthread.h>
  19. #include <inttypes.h>
  20. #include <stdlib.h>
  21. #include <AP_HAL/utility/functor.h>
  22. namespace Linux {
  23. /*
  24. * Interface abstracting threads
  25. */
  26. class Thread {
  27. public:
  28. FUNCTOR_TYPEDEF(task_t, void);
  29. Thread(task_t t) : _task(t) { }
  30. virtual ~Thread() { }
  31. bool start(const char *name, int policy, int prio);
  32. bool is_current_thread();
  33. bool is_started() const { return _started; }
  34. size_t get_stack_usage();
  35. bool set_stack_size(size_t stack_size);
  36. void set_auto_free(bool auto_free) { _auto_free = auto_free; }
  37. virtual bool stop() { return false; }
  38. bool join();
  39. protected:
  40. static void *_run_trampoline(void *arg);
  41. /*
  42. * Run the task assigned in the constructor. May be overriden in case it's
  43. * preferred to use Thread as an interface or when user wants to aggregate
  44. * some initialization or teardown for the thread.
  45. */
  46. virtual bool _run();
  47. void _poison_stack();
  48. task_t _task;
  49. bool _started = false;
  50. bool _should_exit = false;
  51. bool _auto_free = false;
  52. pthread_t _ctx = 0;
  53. struct stack_debug {
  54. uint32_t *start;
  55. uint32_t *end;
  56. } _stack_debug;
  57. size_t _stack_size = 0;
  58. };
  59. class PeriodicThread : public Thread {
  60. public:
  61. PeriodicThread(Thread::task_t t)
  62. : Thread(t)
  63. { }
  64. bool set_rate(uint32_t rate_hz);
  65. bool stop() override;
  66. protected:
  67. bool _run() override;
  68. uint64_t _period_usec = 0;
  69. };
  70. }