Kenji Arai / mbed-os_TYBLE16

Dependents:   TYBLE16_simple_data_logger TYBLE16_MP3_Air

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Thread.h Source File

Thread.h

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2019 ARM Limited
00003  *
00004  * Permission is hereby granted, free of charge, to any person obtaining a copy
00005  * of this software and associated documentation files (the "Software"), to deal
00006  * in the Software without restriction, including without limitation the rights
00007  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
00008  * copies of the Software, and to permit persons to whom the Software is
00009  * furnished to do so, subject to the following conditions:
00010  *
00011  * The above copyright notice and this permission notice shall be included in
00012  * all copies or substantial portions of the Software.
00013  *
00014  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00015  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00016  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00017  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00018  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00019  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
00020  * SOFTWARE.
00021  */
00022 #ifndef THREAD_H
00023 #define THREAD_H
00024 
00025 #include <stdint.h>
00026 #include "rtos/mbed_rtos_types.h"
00027 #include "rtos/mbed_rtos1_types.h"
00028 #include "rtos/mbed_rtos_storage.h"
00029 #include "platform/Callback.h"
00030 #include "platform/mbed_toolchain.h"
00031 #include "platform/NonCopyable.h"
00032 #include "rtos/Semaphore.h"
00033 #include "rtos/Mutex.h"
00034 
00035 #if MBED_CONF_RTOS_PRESENT || defined(DOXYGEN_ONLY) || defined(UNITTEST)
00036 
00037 namespace rtos {
00038 /** \addtogroup rtos-public-api */
00039 /** @{*/
00040 
00041 /**
00042  * \defgroup rtos_Thread Thread class
00043  * @{
00044  */
00045 
00046 /** The Thread class allow defining, creating, and controlling thread functions in the system.
00047  *
00048  *  Example:
00049  *  @code
00050  *  #include "mbed.h"
00051  *  #include "rtos.h"
00052  *
00053  *  Thread thread;
00054  *  DigitalOut led1(LED1);
00055  *  volatile bool running = true;
00056  *
00057  *  // Blink function toggles the led in a long running loop
00058  *  void blink(DigitalOut *led) {
00059  *      while (running) {
00060  *          *led = !*led;
00061  *          wait(1);
00062  *      }
00063  *  }
00064  *
00065  *  // Spawns a thread to run blink for 5 seconds
00066  *  int main() {
00067  *      thread.start(callback(blink, &led1));
00068  *      wait(5);
00069  *      running = false;
00070  *      thread.join();
00071  *  }
00072  *  @endcode
00073  *
00074  * @note
00075  * Memory considerations: The thread control structures will be created on current thread's stack, both for the mbed OS
00076  * and underlying RTOS objects (static or dynamic RTOS memory pools are not being used).
00077  * Additionally the stack memory for this thread will be allocated on the heap, if it wasn't supplied to the constructor.
00078  *
00079  * @note
00080  * MBED_TZ_DEFAULT_ACCESS (default:0) flag can be used to change the default access of all user threads in non-secure mode.
00081  * MBED_TZ_DEFAULT_ACCESS set to 1, means all non-secure user threads have access to call secure functions.
00082  * MBED_TZ_DEFAULT_ACCESS set to 0, means none of the non-secure user thread have access to call secure functions,
00083  * to give access to particular thread used overloaded constructor with `tz_module` as argument during thread creation.
00084  *
00085  * MBED_TZ_DEFAULT_ACCESS is target specific define, should be set in targets.json file for Cortex-M23/M33 devices.
00086  */
00087 
00088 class Thread : private mbed::NonCopyable<Thread> {
00089 public:
00090     /** Allocate a new thread without starting execution
00091       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00092       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00093       @param   stack_mem      pointer to the stack area to be used by this thread (default: nullptr).
00094       @param   name           name to be used for this thread. It has to stay allocated for the lifetime of the thread (default: nullptr)
00095 
00096       @note Default value of tz_module will be MBED_TZ_DEFAULT_ACCESS
00097       @note You cannot call this function from ISR context.
00098     */
00099 
00100     Thread(osPriority priority = osPriorityNormal,
00101            uint32_t stack_size = OS_STACK_SIZE,
00102            unsigned char *stack_mem = nullptr, const char *name = nullptr)
00103     {
00104         constructor(priority, stack_size, stack_mem, name);
00105     }
00106 
00107     /** Allocate a new thread without starting execution
00108       @param   tz_module      trustzone thread identifier (osThreadAttr_t::tz_module)
00109                               Context of RTOS threads in non-secure state must be saved when calling secure functions.
00110                               tz_module ID is used to allocate context memory for threads, and it can be safely set to zero for
00111                               threads not using secure calls at all. See "TrustZone RTOS Context Management" for more details.
00112       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00113       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00114       @param   stack_mem      pointer to the stack area to be used by this thread (default: nullptr).
00115       @param   name           name to be used for this thread. It has to stay allocated for the lifetime of the thread (default: nullptr)
00116 
00117       @note You cannot call this function from ISR context.
00118     */
00119 
00120     Thread(uint32_t tz_module, osPriority priority = osPriorityNormal,
00121            uint32_t stack_size = OS_STACK_SIZE,
00122            unsigned char *stack_mem = nullptr, const char *name = nullptr)
00123     {
00124         constructor(tz_module, priority, stack_size, stack_mem, name);
00125     }
00126 
00127 
00128     /** Starts a thread executing the specified function.
00129       @param   task           function to be executed by this thread.
00130       @return  status code that indicates the execution status of the function.
00131       @note a thread can only be started once
00132 
00133       @note You cannot call this function ISR context.
00134     */
00135     osStatus start(mbed::Callback<void()> task);
00136 
00137     /** Wait for thread to terminate
00138       @return  status code that indicates the execution status of the function.
00139 
00140       @note You cannot call this function from ISR context.
00141     */
00142     osStatus join();
00143 
00144     /** Terminate execution of a thread and remove it from Active Threads
00145       @return  status code that indicates the execution status of the function.
00146 
00147       @note You cannot call this function from ISR context.
00148     */
00149     osStatus terminate();
00150 
00151     /** Set priority of an active thread
00152       @param   priority  new priority value for the thread function.
00153       @return  status code that indicates the execution status of the function.
00154 
00155       @note You cannot call this function from ISR context.
00156     */
00157     osStatus set_priority(osPriority priority);
00158 
00159     /** Get priority of an active thread
00160       @return  current priority value of the thread function.
00161 
00162       @note You cannot call this function from ISR context.
00163     */
00164     osPriority get_priority() const;
00165 
00166     /** Set the specified Thread Flags for the thread.
00167       @param   flags  specifies the flags of the thread that should be set.
00168       @return  thread flags after setting or osFlagsError in case of incorrect parameters.
00169 
00170       @note You may call this function from ISR context.
00171     */
00172     uint32_t flags_set(uint32_t flags);
00173 
00174     /** Set the specified Thread Flags for the thread.
00175       @param   signals  specifies the signal flags of the thread that should be set.
00176       @return  signal flags after setting or osFlagsError in case of incorrect parameters.
00177 
00178       @note You may call this function from ISR context.
00179       @deprecated Other signal_xxx methods have been deprecated in favour of ThisThread::flags functions.
00180                   To match this naming scheme, derived from CMSIS-RTOS2, Thread::flags_set is now provided.
00181     */
00182     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00183                           "Other signal_xxx methods have been deprecated in favour of ThisThread::flags functions. "
00184                           "To match this naming scheme, derived from CMSIS-RTOS2, Thread::flags_set is now provided.")
00185     int32_t signal_set(int32_t signals);
00186 
00187     /** State of the Thread */
00188     enum State {
00189         Inactive,           /**< NOT USED */
00190         Ready,              /**< Ready to run */
00191         Running,            /**< Running */
00192         WaitingDelay,       /**< Waiting for a delay to occur */
00193         WaitingJoin,        /**< Waiting for thread to join. Only happens when using RTX directly. */
00194         WaitingThreadFlag,  /**< Waiting for a thread flag to be set */
00195         WaitingEventFlag,   /**< Waiting for a event flag to be set */
00196         WaitingMutex,       /**< Waiting for a mutex event to occur */
00197         WaitingSemaphore,   /**< Waiting for a semaphore event to occur */
00198         WaitingMemoryPool,  /**< Waiting for a memory pool */
00199         WaitingMessageGet,  /**< Waiting for message to arrive */
00200         WaitingMessagePut,  /**< Waiting for message to be send */
00201         WaitingInterval,    /**< NOT USED */
00202         WaitingOr,          /**< NOT USED */
00203         WaitingAnd,         /**< NOT USED */
00204         WaitingMailbox,     /**< NOT USED (Mail is implemented as MemoryPool and Queue) */
00205 
00206         /* Not in sync with RTX below here */
00207         Deleted,            /**< The task has been deleted or not started */
00208     };
00209 
00210     /** State of this Thread
00211       @return  the State of this Thread
00212 
00213       @note You cannot call this function from ISR context.
00214     */
00215     State get_state() const;
00216 
00217     /** Get the total stack memory size for this Thread
00218       @return  the total stack memory size in bytes
00219 
00220       @note You cannot call this function from ISR context.
00221     */
00222     uint32_t stack_size() const;
00223 
00224     /** Get the currently unused stack memory for this Thread
00225       @return  the currently unused stack memory in bytes
00226 
00227       @note You cannot call this function from ISR context.
00228     */
00229     uint32_t free_stack() const;
00230 
00231     /** Get the currently used stack memory for this Thread
00232       @return  the currently used stack memory in bytes
00233 
00234       @note You cannot call this function from ISR context.
00235     */
00236     uint32_t used_stack() const;
00237 
00238     /** Get the maximum stack memory usage to date for this Thread
00239       @return  the maximum stack memory usage to date in bytes
00240 
00241       @note You cannot call this function from ISR context.
00242     */
00243     uint32_t max_stack() const;
00244 
00245     /** Get thread name
00246       @return  thread name or nullptr if the name was not set.
00247 
00248       @note You may call this function from ISR context.
00249      */
00250     const char *get_name() const;
00251 
00252     /** Get thread id
00253       @return  thread ID for reference by other functions.
00254 
00255       @note You may call this function from ISR context.
00256      */
00257     osThreadId_t get_id() const;
00258 
00259     /** Clears the specified Thread Flags of the currently running thread.
00260       @param   signals  specifies the signal flags of the thread that should be cleared.
00261       @return  signal flags before clearing or osFlagsError in case of incorrect parameters.
00262 
00263       @note You cannot call this function from ISR context.
00264       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::flags_clear.
00265     */
00266     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00267                           "Static methods only affecting current thread cause confusion. "
00268                           "Replaced by ThisThread::flags_clear.")
00269     static int32_t signal_clr(int32_t signals);
00270 
00271     /** Wait for one or more Thread Flags to become signaled for the current RUNNING thread.
00272       @param   signals   wait until all specified signal flags are set or 0 for any single signal flag.
00273       @param   millisec  timeout value. (default: osWaitForever).
00274       @return  event flag information or error code. @note if @a millisec is set to 0 and flag is no set the event carries osOK value.
00275 
00276       @note You cannot call this function from ISR context.
00277       @deprecated Static methods only affecting current thread cause confusion.
00278                   Replaced by ThisThread::flags_wait_all, ThisThread::flags_wait_all_for, ThisThread::flags_wait_any and ThisThread:wait_any_for.
00279     */
00280     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00281                           "Static methods only affecting current thread cause confusion. "
00282                           "Replaced by ThisThread::flags_wait_all, ThisThread::flags_wait_all_for, ThisThread::flags_wait_any and ThisThread:wait_any_for.")
00283     static osEvent signal_wait(int32_t signals, uint32_t millisec = osWaitForever);
00284 
00285     /** Wait for a specified time period in milliseconds
00286       Being tick-based, the delay will be up to the specified time - eg for
00287       a value of 1 the system waits until the next millisecond tick occurs,
00288       leading to a delay of 0-1 milliseconds.
00289       @param   millisec  time delay value
00290       @return  status code that indicates the execution status of the function.
00291 
00292       @note You cannot call this function from ISR context.
00293       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::sleep_for.
00294     */
00295     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00296                           "Static methods only affecting current thread cause confusion. "
00297                           "Replaced by ThisThread::sleep_for.")
00298     static osStatus wait(uint32_t millisec);
00299 
00300     /** Wait until a specified time in millisec
00301       The specified time is according to Kernel::get_ms_count().
00302       @param   millisec absolute time in millisec
00303       @return  status code that indicates the execution status of the function.
00304       @note not callable from interrupt
00305       @note if millisec is equal to or lower than the current tick count, this
00306             returns immediately, either with an error or "osOK".
00307       @note the underlying RTOS may have a limit to the maximum wait time
00308             due to internal 32-bit computations, but this is guaranteed to work if the
00309             delay is <= 0x7fffffff milliseconds (~24 days). If the limit is exceeded,
00310             it may return with an immediate error, or wait for the maximum delay.
00311 
00312       @note You cannot call this function from ISR context.
00313       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::sleep_until.
00314     */
00315     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00316                           "Static methods only affecting current thread cause confusion. "
00317                           "Replaced by ThisThread::sleep_until.")
00318     static osStatus wait_until(uint64_t millisec);
00319 
00320     /** Pass control to next thread that is in state READY.
00321       @return  status code that indicates the execution status of the function.
00322 
00323       @note You cannot call this function from ISR context.
00324       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::sleep_until.
00325     */
00326     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00327                           "Static methods only affecting current thread cause confusion. "
00328                           "Replaced by ThisThread::yield.")
00329     static osStatus yield();
00330 
00331     /** Get the thread id of the current running thread.
00332       @return  thread ID for reference by other functions or nullptr in case of error.
00333 
00334       @note You may call this function from ISR context.
00335       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::get_id.
00336                   Use Thread::get_id for the ID of a specific Thread.
00337     */
00338     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00339                           "Static methods only affecting current thread cause confusion. "
00340                           "Replaced by ThisThread::get_id. Use Thread::get_id for the ID of a specific Thread.")
00341     static osThreadId gettid();
00342 
00343     /** Attach a function to be called by the RTOS idle task
00344       @param   fptr  pointer to the function to be called
00345 
00346       @note You may call this function from ISR context.
00347       @deprecated Static methods affecting system cause confusion. Replaced by Kernel::attach_idle_hook.
00348     */
00349     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00350                           "Static methods affecting system cause confusion. "
00351                           "Replaced by Kernel::attach_idle_hook.")
00352     static void attach_idle_hook(void (*fptr)(void));
00353 
00354     /** Attach a function to be called when a task is killed
00355       @param   fptr  pointer to the function to be called
00356 
00357       @note You may call this function from ISR context.
00358       @deprecated Static methods affecting system cause confusion. Replaced by Kernel::attach_thread_terminate_hook.
00359     */
00360     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00361                           "Static methods affecting system cause confusion. "
00362                           "Replaced by Kernel::attach_thread_terminate_hook.")
00363     static void attach_terminate_hook(void (*fptr)(osThreadId id));
00364 
00365     /** Thread destructor
00366      *
00367      * @note You cannot call this function from ISR context.
00368      */
00369     virtual ~Thread();
00370 
00371 private:
00372     // Required to share definitions without
00373     // delegated constructors
00374     void constructor(osPriority priority = osPriorityNormal,
00375                      uint32_t stack_size = OS_STACK_SIZE,
00376                      unsigned char *stack_mem = nullptr,
00377                      const char *name = nullptr);
00378     void constructor(uint32_t tz_module,
00379                      osPriority priority = osPriorityNormal,
00380                      uint32_t stack_size = OS_STACK_SIZE,
00381                      unsigned char *stack_mem = nullptr,
00382                      const char *name = nullptr);
00383     static void _thunk(void *thread_ptr);
00384 
00385     mbed::Callback<void()>     _task;
00386     osThreadId_t               _tid;
00387     osThreadAttr_t             _attr;
00388     bool                       _dynamic_stack;
00389     Semaphore                  _join_sem;
00390     mutable Mutex              _mutex;
00391     mbed_rtos_storage_thread_t _obj_mem;
00392     bool                       _finished;
00393 };
00394 /** @}*/
00395 /** @}*/
00396 }
00397 #endif
00398 
00399 #endif