takashi kadono / Mbed OS Nucleo_446

Dependencies:   ssd1331

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-2012 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 "cmsis_os2.h"
00027 #include "mbed_rtos1_types.h"
00028 #include "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 namespace rtos {
00036 /** \addtogroup rtos */
00037 /** @{*/
00038 /**
00039  * \defgroup rtos_Thread Thread class
00040  * @{
00041  */
00042 
00043 /** The Thread class allow defining, creating, and controlling thread functions in the system.
00044  *
00045  *  Example:
00046  *  @code
00047  *  #include "mbed.h"
00048  *  #include "rtos.h"
00049  *
00050  *  Thread thread;
00051  *  DigitalOut led1(LED1);
00052  *  volatile bool running = true;
00053  *
00054  *  // Blink function toggles the led in a long running loop
00055  *  void blink(DigitalOut *led) {
00056  *      while (running) {
00057  *          *led = !*led;
00058  *          wait(1);
00059  *      }
00060  *  }
00061  *
00062  *  // Spawns a thread to run blink for 5 seconds
00063  *  int main() {
00064  *      thread.start(callback(blink, &led1));
00065  *      wait(5);
00066  *      running = false;
00067  *      thread.join();
00068  *  }
00069  *  @endcode
00070  *
00071  * @note
00072  * Memory considerations: The thread control structures will be created on current thread's stack, both for the mbed OS
00073  * and underlying RTOS objects (static or dynamic RTOS memory pools are not being used).
00074  * Additionally the stack memory for this thread will be allocated on the heap, if it wasn't supplied to the constructor.
00075  *
00076  * @note
00077  * MBED_TZ_DEFAULT_ACCESS (default:0) flag can be used to change the default access of all user threads in non-secure mode.
00078  * MBED_TZ_DEFAULT_ACCESS set to 1, means all non-secure user threads have access to call secure functions.
00079  * MBED_TZ_DEFAULT_ACCESS set to 0, means none of the non-secure user thread have access to call secure functions,
00080  * to give access to particular thread used overloaded constructor with `tz_module` as argument during thread creation.
00081  *
00082  * MBED_TZ_DEFAULT_ACCESS is target specific define, should be set in targets.json file for Cortex-M23/M33 devices.
00083  */
00084 
00085 class Thread : private mbed::NonCopyable<Thread> {
00086 public:
00087     /** Allocate a new thread without starting execution
00088       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00089       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00090       @param   stack_mem      pointer to the stack area to be used by this thread (default: NULL).
00091       @param   name           name to be used for this thread. It has to stay allocated for the lifetime of the thread (default: NULL)
00092 
00093       @note Default value of tz_module will be MBED_TZ_DEFAULT_ACCESS
00094       @note You cannot call this function from ISR context.
00095     */
00096 
00097     Thread(osPriority priority = osPriorityNormal,
00098            uint32_t stack_size = OS_STACK_SIZE,
00099            unsigned char *stack_mem = NULL, const char *name = NULL)
00100     {
00101         constructor(priority, stack_size, stack_mem, name);
00102     }
00103 
00104     /** Allocate a new thread without starting execution
00105       @param   tz_module      trustzone thread identifier (osThreadAttr_t::tz_module)
00106                               Context of RTOS threads in non-secure state must be saved when calling secure functions.
00107                               tz_module ID is used to allocate context memory for threads, and it can be safely set to zero for
00108                               threads not using secure calls at all. See "TrustZone RTOS Context Management" for more details.
00109       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00110       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00111       @param   stack_mem      pointer to the stack area to be used by this thread (default: NULL).
00112       @param   name           name to be used for this thread. It has to stay allocated for the lifetime of the thread (default: NULL)
00113 
00114       @note You cannot call this function from ISR context.
00115     */
00116 
00117     Thread(uint32_t tz_module, osPriority priority = osPriorityNormal,
00118            uint32_t stack_size = OS_STACK_SIZE,
00119            unsigned char *stack_mem = NULL, const char *name = NULL)
00120     {
00121         constructor(tz_module, priority, stack_size, stack_mem, name);
00122     }
00123 
00124 
00125     /** Create a new thread, and start it executing the specified function.
00126       @param   task           function to be executed by this thread.
00127       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00128       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00129       @param   stack_mem      pointer to the stack area to be used by this thread (default: NULL).
00130       @deprecated
00131         Thread-spawning constructors hide errors. Replaced by thread.start(task).
00132 
00133         @code
00134         Thread thread(priority, stack_size, stack_mem);
00135 
00136         osStatus status = thread.start(task);
00137         if (status != osOK) {
00138             error("oh no!");
00139         }
00140         @endcode
00141 
00142       @note You cannot call this function from ISR context.
00143     */
00144     MBED_DEPRECATED_SINCE("mbed-os-5.1",
00145                           "Thread-spawning constructors hide errors. "
00146                           "Replaced by thread.start(task).")
00147     Thread(mbed::Callback<void()> task,
00148            osPriority priority = osPriorityNormal,
00149            uint32_t stack_size = OS_STACK_SIZE,
00150            unsigned char *stack_mem = NULL)
00151     {
00152         constructor(task, priority, stack_size, stack_mem);
00153     }
00154 
00155     /** Create a new thread, and start it executing the specified function.
00156       @param   argument       pointer that is passed to the thread function as start argument. (default: NULL).
00157       @param   task           argument to task.
00158       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00159       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00160       @param   stack_mem      pointer to the stack area to be used by this thread (default: NULL).
00161       @deprecated
00162         Thread-spawning constructors hide errors. Replaced by thread.start(callback(task, argument)).
00163 
00164         @code
00165         Thread thread(priority, stack_size, stack_mem);
00166 
00167         osStatus status = thread.start(callback(task, argument));
00168         if (status != osOK) {
00169             error("oh no!");
00170         }
00171         @endcode
00172 
00173         @note You cannot call this function from ISR context.
00174     */
00175     template <typename T>
00176     MBED_DEPRECATED_SINCE("mbed-os-5.1",
00177                           "Thread-spawning constructors hide errors. "
00178                           "Replaced by thread.start(callback(task, argument)).")
00179     Thread(T *argument, void (T::*task)(),
00180            osPriority priority = osPriorityNormal,
00181            uint32_t stack_size = OS_STACK_SIZE,
00182            unsigned char *stack_mem = NULL)
00183     {
00184         constructor(mbed::callback(task, argument),
00185                     priority, stack_size, stack_mem);
00186     }
00187 
00188     /** Create a new thread, and start it executing the specified function.
00189       @param   argument       pointer that is passed to the thread function as start argument. (default: NULL).
00190       @param   task           argument to task.
00191       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00192       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00193       @param   stack_mem      pointer to the stack area to be used by this thread (default: NULL).
00194       @deprecated
00195         Thread-spawning constructors hide errors. Replaced by thread.start(callback(task, argument)).
00196 
00197         @code
00198         Thread thread(priority, stack_size, stack_mem);
00199 
00200         osStatus status = thread.start(callback(task, argument));
00201         if (status != osOK) {
00202             error("oh no!");
00203         }
00204         @endcode
00205 
00206       @note You cannot call this function from ISR context.
00207     */
00208     template <typename T>
00209     MBED_DEPRECATED_SINCE("mbed-os-5.1",
00210                           "Thread-spawning constructors hide errors. "
00211                           "Replaced by thread.start(callback(task, argument)).")
00212     Thread(T *argument, void (*task)(T *),
00213            osPriority priority = osPriorityNormal,
00214            uint32_t stack_size = OS_STACK_SIZE,
00215            unsigned char *stack_mem = NULL)
00216     {
00217         constructor(mbed::callback(task, argument),
00218                     priority, stack_size, stack_mem);
00219     }
00220 
00221     /** Create a new thread, and start it executing the specified function.
00222         Provided for backwards compatibility
00223       @param   task           function to be executed by this thread.
00224       @param   argument       pointer that is passed to the thread function as start argument. (default: NULL).
00225       @param   priority       initial priority of the thread function. (default: osPriorityNormal).
00226       @param   stack_size     stack size (in bytes) requirements for the thread function. (default: OS_STACK_SIZE).
00227       @param   stack_mem      pointer to the stack area to be used by this thread (default: NULL).
00228       @deprecated
00229         Thread-spawning constructors hide errors. Replaced by thread.start(callback(task, argument)).
00230 
00231         @code
00232         Thread thread(priority, stack_size, stack_mem);
00233 
00234         osStatus status = thread.start(callback(task, argument));
00235         if (status != osOK) {
00236             error("oh no!");
00237         }
00238         @endcode
00239 
00240         @note You cannot call this function from ISR context.
00241     */
00242     MBED_DEPRECATED_SINCE("mbed-os-5.1",
00243                           "Thread-spawning constructors hide errors. "
00244                           "Replaced by thread.start(callback(task, argument)).")
00245     Thread(void (*task)(void const *argument), void *argument = NULL,
00246            osPriority priority = osPriorityNormal,
00247            uint32_t stack_size = OS_STACK_SIZE,
00248            unsigned char *stack_mem = NULL)
00249     {
00250         constructor(mbed::callback((void (*)(void *))task, argument),
00251                     priority, stack_size, stack_mem);
00252     }
00253 
00254     /** Starts a thread executing the specified function.
00255       @param   task           function to be executed by this thread.
00256       @return  status code that indicates the execution status of the function.
00257       @note a thread can only be started once
00258 
00259       @note You cannot call this function ISR context.
00260     */
00261     osStatus start(mbed::Callback<void()> task);
00262 
00263     /** Starts a thread executing the specified function.
00264       @param   obj            argument to task
00265       @param   method         function to be executed by this thread.
00266       @return  status code that indicates the execution status of the function.
00267       @deprecated
00268           The start function does not support cv-qualifiers. Replaced by start(callback(obj, method)).
00269 
00270       @note You cannot call this function from ISR context.
00271     */
00272     template <typename T, typename M>
00273     MBED_DEPRECATED_SINCE("mbed-os-5.1",
00274                           "The start function does not support cv-qualifiers. "
00275                           "Replaced by thread.start(callback(obj, method)).")
00276     osStatus start(T *obj, M method)
00277     {
00278         return start(mbed::callback(obj, method));
00279     }
00280 
00281     /** Wait for thread to terminate
00282       @return  status code that indicates the execution status of the function.
00283 
00284       @note You cannot call this function from ISR context.
00285     */
00286     osStatus join();
00287 
00288     /** Terminate execution of a thread and remove it from Active Threads
00289       @return  status code that indicates the execution status of the function.
00290 
00291       @note You cannot call this function from ISR context.
00292     */
00293     osStatus terminate();
00294 
00295     /** Set priority of an active thread
00296       @param   priority  new priority value for the thread function.
00297       @return  status code that indicates the execution status of the function.
00298 
00299       @note You cannot call this function from ISR context.
00300     */
00301     osStatus set_priority(osPriority priority);
00302 
00303     /** Get priority of an active thread
00304       @return  current priority value of the thread function.
00305 
00306       @note You cannot call this function from ISR context.
00307     */
00308     osPriority get_priority() const;
00309 
00310     /** Set the specified Thread Flags for the thread.
00311       @param   flags  specifies the flags of the thread that should be set.
00312       @return  thread flags after setting or osFlagsError in case of incorrect parameters.
00313 
00314       @note You may call this function from ISR context.
00315     */
00316     uint32_t flags_set(uint32_t flags);
00317 
00318     /** Set the specified Thread Flags for the thread.
00319       @param   signals  specifies the signal flags of the thread that should be set.
00320       @return  signal flags after setting or osFlagsError in case of incorrect parameters.
00321 
00322       @note You may call this function from ISR context.
00323       @deprecated Other signal_xxx methods have been deprecated in favour of ThisThread::flags functions.
00324                   To match this naming scheme, derived from CMSIS-RTOS2, Thread::flags_set is now provided.
00325     */
00326     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00327                           "Other signal_xxx methods have been deprecated in favour of ThisThread::flags functions. "
00328                           "To match this naming scheme, derived from CMSIS-RTOS2, Thread::flags_set is now provided.")
00329     int32_t signal_set(int32_t signals);
00330 
00331     /** State of the Thread */
00332     enum State {
00333         Inactive,           /**< NOT USED */
00334         Ready,              /**< Ready to run */
00335         Running,            /**< Running */
00336         WaitingDelay,       /**< Waiting for a delay to occur */
00337         WaitingJoin,        /**< Waiting for thread to join. Only happens when using RTX directly. */
00338         WaitingThreadFlag,  /**< Waiting for a thread flag to be set */
00339         WaitingEventFlag,   /**< Waiting for a event flag to be set */
00340         WaitingMutex,       /**< Waiting for a mutex event to occur */
00341         WaitingSemaphore,   /**< Waiting for a semaphore event to occur */
00342         WaitingMemoryPool,  /**< Waiting for a memory pool */
00343         WaitingMessageGet,  /**< Waiting for message to arrive */
00344         WaitingMessagePut,  /**< Waiting for message to be send */
00345         WaitingInterval,    /**< NOT USED */
00346         WaitingOr,          /**< NOT USED */
00347         WaitingAnd,         /**< NOT USED */
00348         WaitingMailbox,     /**< NOT USED (Mail is implemented as MemoryPool and Queue) */
00349 
00350         /* Not in sync with RTX below here */
00351         Deleted,            /**< The task has been deleted or not started */
00352     };
00353 
00354     /** State of this Thread
00355       @return  the State of this Thread
00356 
00357       @note You cannot call this function from ISR context.
00358     */
00359     State get_state() const;
00360 
00361     /** Get the total stack memory size for this Thread
00362       @return  the total stack memory size in bytes
00363 
00364       @note You cannot call this function from ISR context.
00365     */
00366     uint32_t stack_size() const;
00367 
00368     /** Get the currently unused stack memory for this Thread
00369       @return  the currently unused stack memory in bytes
00370 
00371       @note You cannot call this function from ISR context.
00372     */
00373     uint32_t free_stack() const;
00374 
00375     /** Get the currently used stack memory for this Thread
00376       @return  the currently used stack memory in bytes
00377 
00378       @note You cannot call this function from ISR context.
00379     */
00380     uint32_t used_stack() const;
00381 
00382     /** Get the maximum stack memory usage to date for this Thread
00383       @return  the maximum stack memory usage to date in bytes
00384 
00385       @note You cannot call this function from ISR context.
00386     */
00387     uint32_t max_stack() const;
00388 
00389     /** Get thread name
00390       @return  thread name or NULL if the name was not set.
00391 
00392       @note You may call this function from ISR context.
00393      */
00394     const char *get_name() const;
00395 
00396     /** Get thread id
00397       @return  thread ID for reference by other functions.
00398 
00399       @note You may call this function from ISR context.
00400      */
00401     osThreadId_t get_id() const;
00402 
00403     /** Clears the specified Thread Flags of the currently running thread.
00404       @param   signals  specifies the signal flags of the thread that should be cleared.
00405       @return  signal flags before clearing or osFlagsError in case of incorrect parameters.
00406 
00407       @note You cannot call this function from ISR context.
00408       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::flags_clear.
00409     */
00410     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00411                           "Static methods only affecting current thread cause confusion. "
00412                           "Replaced by ThisThread::flags_clear.")
00413     static int32_t signal_clr(int32_t signals);
00414 
00415     /** Wait for one or more Thread Flags to become signaled for the current RUNNING thread.
00416       @param   signals   wait until all specified signal flags are set or 0 for any single signal flag.
00417       @param   millisec  timeout value or 0 in case of no time-out. (default: osWaitForever).
00418       @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.
00419 
00420       @note You cannot call this function from ISR context.
00421       @deprecated Static methods only affecting current thread cause confusion.
00422                   Replaced by ThisThread::flags_wait_all, ThisThread::flags_wait_all_for, ThisThread::flags_wait_any and ThisThread:wait_any_for.
00423     */
00424     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00425                           "Static methods only affecting current thread cause confusion. "
00426                           "Replaced by ThisThread::flags_wait_all, ThisThread::flags_wait_all_for, ThisThread::flags_wait_any and ThisThread:wait_any_for.")
00427     static osEvent signal_wait(int32_t signals, uint32_t millisec = osWaitForever);
00428 
00429     /** Wait for a specified time period in milliseconds
00430       Being tick-based, the delay will be up to the specified time - eg for
00431       a value of 1 the system waits until the next millisecond tick occurs,
00432       leading to a delay of 0-1 milliseconds.
00433       @param   millisec  time delay value
00434       @return  status code that indicates the execution status of the function.
00435 
00436       @note You cannot call this function from ISR context.
00437       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::sleep_for.
00438     */
00439     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00440                           "Static methods only affecting current thread cause confusion. "
00441                           "Replaced by ThisThread::sleep_for.")
00442     static osStatus wait(uint32_t millisec);
00443 
00444     /** Wait until a specified time in millisec
00445       The specified time is according to Kernel::get_ms_count().
00446       @param   millisec absolute time in millisec
00447       @return  status code that indicates the execution status of the function.
00448       @note not callable from interrupt
00449       @note if millisec is equal to or lower than the current tick count, this
00450             returns immediately, either with an error or "osOK".
00451       @note the underlying RTOS may have a limit to the maximum wait time
00452             due to internal 32-bit computations, but this is guaranteed to work if the
00453             delay is <= 0x7fffffff milliseconds (~24 days). If the limit is exceeded,
00454             it may return with an immediate error, or wait for the maximum delay.
00455 
00456       @note You cannot call this function from ISR context.
00457       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::sleep_until.
00458     */
00459     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00460                           "Static methods only affecting current thread cause confusion. "
00461                           "Replaced by ThisThread::sleep_until.")
00462     static osStatus wait_until(uint64_t millisec);
00463 
00464     /** Pass control to next thread that is in state READY.
00465       @return  status code that indicates the execution status of the function.
00466 
00467       @note You cannot call this function from ISR context.
00468       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::sleep_until.
00469     */
00470     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00471                           "Static methods only affecting current thread cause confusion. "
00472                           "Replaced by ThisThread::yield.")
00473     static osStatus yield();
00474 
00475     /** Get the thread id of the current running thread.
00476       @return  thread ID for reference by other functions or NULL in case of error.
00477 
00478       @note You may call this function from ISR context.
00479       @deprecated Static methods only affecting current thread cause confusion. Replaced by ThisThread::get_id.
00480                   Use Thread::get_id for the ID of a specific Thread.
00481     */
00482     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00483                           "Static methods only affecting current thread cause confusion. "
00484                           "Replaced by ThisThread::get_id. Use Thread::get_id for the ID of a specific Thread.")
00485     static osThreadId gettid();
00486 
00487     /** Attach a function to be called by the RTOS idle task
00488       @param   fptr  pointer to the function to be called
00489 
00490       @note You may call this function from ISR context.
00491       @deprecated Static methods affecting system cause confusion. Replaced by Kernel::attach_idle_hook.
00492     */
00493     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00494                           "Static methods affecting system cause confusion. "
00495                           "Replaced by Kernel::attach_idle_hook.")
00496     static void attach_idle_hook(void (*fptr)(void));
00497 
00498     /** Attach a function to be called when a task is killed
00499       @param   fptr  pointer to the function to be called
00500 
00501       @note You may call this function from ISR context.
00502       @deprecated Static methods affecting system cause confusion. Replaced by Kernel::attach_thread_terminate_hook.
00503     */
00504     MBED_DEPRECATED_SINCE("mbed-os-5.10",
00505                           "Static methods affecting system cause confusion. "
00506                           "Replaced by Kernel::attach_thread_terminate_hook.")
00507     static void attach_terminate_hook(void (*fptr)(osThreadId id));
00508 
00509     /** Thread destructor
00510      *
00511      * @note You cannot call this function from ISR context.
00512      */
00513     virtual ~Thread();
00514 
00515 private:
00516     // Required to share definitions without
00517     // delegated constructors
00518     void constructor(osPriority priority = osPriorityNormal,
00519                      uint32_t stack_size = OS_STACK_SIZE,
00520                      unsigned char *stack_mem = NULL,
00521                      const char *name = NULL);
00522     void constructor(mbed::Callback<void()> task,
00523                      osPriority priority = osPriorityNormal,
00524                      uint32_t stack_size = OS_STACK_SIZE,
00525                      unsigned char *stack_mem = NULL,
00526                      const char *name = NULL);
00527     void constructor(uint32_t tz_module,
00528                      osPriority priority = osPriorityNormal,
00529                      uint32_t stack_size = OS_STACK_SIZE,
00530                      unsigned char *stack_mem = NULL,
00531                      const char *name = NULL);
00532     static void _thunk(void *thread_ptr);
00533 
00534     mbed::Callback<void()>     _task;
00535     osThreadId_t               _tid;
00536     osThreadAttr_t             _attr;
00537     bool                       _dynamic_stack;
00538     Semaphore                  _join_sem;
00539     mutable Mutex              _mutex;
00540     mbed_rtos_storage_thread_t _obj_mem;
00541     bool                       _finished;
00542 };
00543 /** @}*/
00544 /** @}*/
00545 }
00546 #endif
00547 
00548