1.. _system_threads_v2: 2 3System Threads 4############## 5 6.. contents:: 7 :local: 8 :depth: 2 9 10A :dfn:`system thread` is a thread that the kernel spawns automatically 11during system initialization. 12 13The kernel spawns the following system threads: 14 15**Main thread** 16 This thread performs kernel initialization, then calls the application's 17 :c:func:`main` function (if one is defined). 18 19 By default, the main thread uses the highest configured preemptible thread 20 priority (i.e. 0). If the kernel is not configured to support preemptible 21 threads, the main thread uses the lowest configured cooperative thread 22 priority (i.e. -1). 23 24 The main thread is an essential thread while it is performing kernel 25 initialization or executing the application's :c:func:`main` function; 26 this means a fatal system error is raised if the thread aborts. If 27 :c:func:`main` is not defined, or if it executes and then does a normal 28 return, the main thread terminates normally and no error is raised. 29 30**Idle thread** 31 This thread executes when there is no other work for the system to do. 32 If possible, the idle thread activates the board's power management support 33 to save power; otherwise, the idle thread simply performs a "do nothing" 34 loop. The idle thread remains in existence as long as the system is running 35 and never terminates. 36 37 The idle thread always uses the lowest configured thread priority. 38 39 The idle thread is an essential thread, which means a fatal system error 40 is raised if the thread aborts. 41 42Additional system threads may also be spawned, depending on the kernel 43and board configuration options specified by the application. For example, 44enabling the system workqueue spawns a system thread 45that services the work items submitted to it. (See :ref:`workqueues_v2`.) 46 47Implementation 48************** 49 50Writing a main() function 51========================= 52 53An application-supplied ``main()`` function begins executing once 54kernel initialization is complete. The kernel does not pass any arguments 55to the function, unless ``CONFIG_BOOTARGS`` is selected. In such case the 56kernel passes arguments to it and ``main(int, char **)`` can be used. 57 58The following code outlines a trivial ``main(void)`` function. 59The function used by a real application can be as complex as needed. 60 61.. code-block:: c 62 63 int main(void) 64 { 65 /* initialize a semaphore */ 66 ... 67 68 /* register an ISR that gives the semaphore */ 69 ... 70 71 /* monitor the semaphore forever */ 72 while (1) { 73 /* wait for the semaphore to be given by the ISR */ 74 ... 75 /* do whatever processing is now needed */ 76 ... 77 } 78 } 79 80Suggested Uses 81************** 82 83Use the main thread to perform thread-based processing in an application 84that only requires a single thread, rather than defining an additional 85application-specific thread. 86