Line data Source code
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 : 19 : #include <pthread.h> 20 : #include <inttypes.h> 21 : #include <stdlib.h> 22 : 23 : #include <AP_HAL/utility/functor.h> 24 : 25 : namespace Linux { 26 : 27 : /* 28 : * Interface abstracting threads 29 : */ 30 : class Thread { 31 : public: 32 : FUNCTOR_TYPEDEF(task_t, void); 33 : 34 196 : Thread(task_t t) : _task(t) { } 35 : 36 196 : virtual ~Thread() { } 37 : 38 : bool start(const char *name, int policy, int prio); 39 : 40 : bool is_current_thread(); 41 : 42 4 : bool is_started() const { return _started; } 43 : 44 : size_t get_stack_usage(); 45 : 46 : bool set_stack_size(size_t stack_size); 47 : 48 0 : void set_auto_free(bool auto_free) { _auto_free = auto_free; } 49 : 50 0 : virtual bool stop() { return false; } 51 : 52 : bool join(); 53 : 54 : protected: 55 : static void *_run_trampoline(void *arg); 56 : 57 : /* 58 : * Run the task assigned in the constructor. May be overriden in case it's 59 : * preferred to use Thread as an interface or when user wants to aggregate 60 : * some initialization or teardown for the thread. 61 : */ 62 : virtual bool _run(); 63 : 64 : void _poison_stack(); 65 : 66 : task_t _task; 67 : bool _started = false; 68 : bool _should_exit = false; 69 : bool _auto_free = false; 70 : pthread_t _ctx = 0; 71 : 72 : struct stack_debug { 73 : uint32_t *start; 74 : uint32_t *end; 75 : } _stack_debug; 76 : 77 : size_t _stack_size = 0; 78 : }; 79 : 80 : class PeriodicThread : public Thread { 81 : public: 82 193 : PeriodicThread(Thread::task_t t) 83 193 : : Thread(t) 84 193 : { } 85 : 86 : bool set_rate(uint32_t rate_hz); 87 : 88 : bool stop() override; 89 : 90 : protected: 91 : bool _run() override; 92 : 93 : uint64_t _period_usec = 0; 94 : }; 95 : 96 : }