Zephyr Project API 4.0.0
A Scalable Open Source RTOS
Loading...
Searching...
No Matches
Thread APIs

Data Structures

struct  k_thread
 Thread Structure. More...
 

Macros

#define K_ESSENTIAL   (BIT(0))
 system thread that must not abort
 
#define K_FP_IDX   1
 
#define K_FP_REGS   (BIT(K_FP_IDX))
 FPU registers are managed by context switch.
 
#define K_USER   (BIT(2))
 user mode thread
 
#define K_INHERIT_PERMS   (BIT(3))
 Inherit Permissions.
 
#define K_CALLBACK_STATE   (BIT(4))
 Callback item state.
 
#define K_DSP_IDX   6
 DSP registers are managed by context switch.
 
#define K_DSP_REGS   (BIT(K_DSP_IDX))
 
#define K_AGU_IDX   7
 AGU registers are managed by context switch.
 
#define K_AGU_REGS   (BIT(K_AGU_IDX))
 
#define K_SSE_REGS   (BIT(7))
 FP and SSE registers are managed by context switch on x86.
 
#define k_thread_access_grant(thread, ...)    FOR_EACH_FIXED_ARG(k_object_access_grant, (;), (thread), __VA_ARGS__)
 Grant a thread access to a set of kernel objects.
 
#define K_THREAD_DEFINE(name, stack_size, entry, p1, p2, p3, prio, options, delay)
 Statically define and initialize a thread.
 
#define K_KERNEL_THREAD_DEFINE(name, stack_size, entry, p1, p2, p3, prio, options, delay)
 Statically define and initialize a thread intended to run only in kernel mode.
 

Typedefs

typedef void(* k_thread_user_cb_t) (const struct k_thread *thread, void *user_data)
 

Functions

void k_thread_foreach (k_thread_user_cb_t user_cb, void *user_data)
 Iterate over all the threads in the system.
 
void k_thread_foreach_filter_by_cpu (unsigned int cpu, k_thread_user_cb_t user_cb, void *user_data)
 Iterate over all the threads in running on specified cpu.
 
void k_thread_foreach_unlocked (k_thread_user_cb_t user_cb, void *user_data)
 Iterate over all the threads in the system without locking.
 
void k_thread_foreach_unlocked_filter_by_cpu (unsigned int cpu, k_thread_user_cb_t user_cb, void *user_data)
 Iterate over the threads in running on current cpu without locking.
 
k_thread_stack_tk_thread_stack_alloc (size_t size, int flags)
 Dynamically allocate a thread stack.
 
int k_thread_stack_free (k_thread_stack_t *stack)
 Free a dynamically allocated thread stack.
 
k_tid_t k_thread_create (struct k_thread *new_thread, k_thread_stack_t *stack, size_t stack_size, k_thread_entry_t entry, void *p1, void *p2, void *p3, int prio, uint32_t options, k_timeout_t delay)
 Create a thread.
 
FUNC_NORETURN void k_thread_user_mode_enter (k_thread_entry_t entry, void *p1, void *p2, void *p3)
 Drop a thread's privileges permanently to user mode.
 
static void k_thread_heap_assign (struct k_thread *thread, struct k_heap *heap)
 Assign a resource memory pool to a thread.
 
int k_thread_join (struct k_thread *thread, k_timeout_t timeout)
 Sleep until a thread exits.
 
int32_t k_sleep (k_timeout_t timeout)
 Put the current thread to sleep.
 
static int32_t k_msleep (int32_t ms)
 Put the current thread to sleep.
 
int32_t k_usleep (int32_t us)
 Put the current thread to sleep with microsecond resolution.
 
void k_busy_wait (uint32_t usec_to_wait)
 Cause the current thread to busy wait.
 
bool k_can_yield (void)
 Check whether it is possible to yield in the current context.
 
void k_yield (void)
 Yield the current thread.
 
void k_wakeup (k_tid_t thread)
 Wake up a sleeping thread.
 
__attribute_const__ k_tid_t k_sched_current_thread_query (void)
 Query thread ID of the current thread.
 
static __attribute_const__ k_tid_t k_current_get (void)
 Get thread ID of the current thread.
 
void k_thread_abort (k_tid_t thread)
 Abort a thread.
 
void k_thread_start (k_tid_t thread)
 Start an inactive thread.
 
k_ticks_t k_thread_timeout_expires_ticks (const struct k_thread *thread)
 Get time when a thread wakes up, in system ticks.
 
k_ticks_t k_thread_timeout_remaining_ticks (const struct k_thread *thread)
 Get time remaining before a thread wakes up, in system ticks.
 
int k_thread_priority_get (k_tid_t thread)
 Get a thread's priority.
 
void k_thread_priority_set (k_tid_t thread, int prio)
 Set a thread's priority.
 
void k_thread_deadline_set (k_tid_t thread, int deadline)
 Set deadline expiration time for scheduler.
 
int k_thread_cpu_mask_clear (k_tid_t thread)
 Sets all CPU enable masks to zero.
 
int k_thread_cpu_mask_enable_all (k_tid_t thread)
 Sets all CPU enable masks to one.
 
int k_thread_cpu_mask_enable (k_tid_t thread, int cpu)
 Enable thread to run on specified CPU.
 
int k_thread_cpu_mask_disable (k_tid_t thread, int cpu)
 Prevent thread to run on specified CPU.
 
int k_thread_cpu_pin (k_tid_t thread, int cpu)
 Pin a thread to a CPU.
 
void k_thread_suspend (k_tid_t thread)
 Suspend a thread.
 
void k_thread_resume (k_tid_t thread)
 Resume a suspended thread.
 
void k_sched_time_slice_set (int32_t slice, int prio)
 Set time-slicing period and scope.
 
void k_thread_time_slice_set (struct k_thread *th, int32_t slice_ticks, k_thread_timeslice_fn_t expired, void *data)
 Set thread time slice.
 
void k_sched_lock (void)
 Lock the scheduler.
 
void k_sched_unlock (void)
 Unlock the scheduler.
 
void k_thread_custom_data_set (void *value)
 Set current thread's custom data.
 
void * k_thread_custom_data_get (void)
 Get current thread's custom data.
 
int k_thread_name_set (k_tid_t thread, const char *str)
 Set current thread name.
 
const char * k_thread_name_get (k_tid_t thread)
 Get thread name.
 
int k_thread_name_copy (k_tid_t thread, char *buf, size_t size)
 Copy the thread name into a supplied buffer.
 
const char * k_thread_state_str (k_tid_t thread_id, char *buf, size_t buf_size)
 Get thread state string.
 

Detailed Description

Macro Definition Documentation

◆ K_AGU_IDX

#define K_AGU_IDX   7

#include <include/zephyr/kernel.h>

AGU registers are managed by context switch.

This option indicates that the thread uses the ARC processor's XY memory and DSP feature. Often used with

CONFIG_ARC_AGU_SHARING 

. No effect if

CONFIG_ARC_AGU_SHARING 

is not enabled.

◆ K_AGU_REGS

#define K_AGU_REGS   (BIT(K_AGU_IDX))

◆ K_CALLBACK_STATE

#define K_CALLBACK_STATE   (BIT(4))

#include <include/zephyr/kernel.h>

Callback item state.

This is a single bit of state reserved for "callback manager" utilities (p4wq initially) who need to track operations invoked from within a user-provided callback they have been invoked. Effectively it serves as a tiny bit of zero-overhead TLS data.

◆ K_DSP_IDX

#define K_DSP_IDX   6

#include <include/zephyr/kernel.h>

DSP registers are managed by context switch.

This option indicates that the thread uses the CPU's DSP registers. This instructs the kernel to take additional steps to save and restore the contents of these registers when scheduling the thread. No effect if

CONFIG_DSP_SHARING 

is not enabled.

◆ K_DSP_REGS

#define K_DSP_REGS   (BIT(K_DSP_IDX))

◆ K_ESSENTIAL

#define K_ESSENTIAL   (BIT(0))

#include <include/zephyr/kernel.h>

system thread that must not abort

◆ K_FP_IDX

#define K_FP_IDX   1

◆ K_FP_REGS

#define K_FP_REGS   (BIT(K_FP_IDX))

#include <include/zephyr/kernel.h>

FPU registers are managed by context switch.

This option indicates that the thread uses the CPU's floating point registers. This instructs the kernel to take additional steps to save and restore the contents of these registers when scheduling the thread. No effect if

CONFIG_FPU_SHARING 

is not enabled.

◆ K_INHERIT_PERMS

#define K_INHERIT_PERMS   (BIT(3))

#include <include/zephyr/kernel.h>

Inherit Permissions.

Indicates that the thread being created should inherit all kernel object permissions from the thread that created it. No effect if

CONFIG_USERSPACE 

is not enabled.

◆ K_KERNEL_THREAD_DEFINE

#define K_KERNEL_THREAD_DEFINE (   name,
  stack_size,
  entry,
  p1,
  p2,
  p3,
  prio,
  options,
  delay 
)

#include <include/zephyr/kernel.h>

Value:
K_KERNEL_STACK_DEFINE(_k_thread_stack_##name, stack_size); \
Z_THREAD_COMMON_DEFINE(name, stack_size, entry, p1, p2, p3, \
prio, options, delay)
#define K_KERNEL_STACK_DEFINE(sym, size)
Define a toplevel kernel stack memory region.
Definition thread_stack.h:214

Statically define and initialize a thread intended to run only in kernel mode.

The thread may be scheduled for immediate execution or a delayed start.

Thread options are architecture-specific, and can include K_ESSENTIAL, K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating them using "|" (the logical OR operator).

The ID of the thread can be accessed using:

extern const k_tid_t <name>;
Note
Threads defined by this can only run in kernel mode, and cannot be transformed into user thread via k_thread_user_mode_enter().
Warning
Depending on the architecture, the stack size (stack_size) may need to be multiples of CONFIG_MMU_PAGE_SIZE (if MMU) or in power-of-two size (if MPU).
Parameters
nameName of the thread.
stack_sizeStack size in bytes.
entryThread entry function.
p11st entry point parameter.
p22nd entry point parameter.
p33rd entry point parameter.
prioThread priority.
optionsThread options.
delayScheduling delay (in milliseconds), zero for no delay.

◆ K_SSE_REGS

#define K_SSE_REGS   (BIT(7))

#include <include/zephyr/kernel.h>

FP and SSE registers are managed by context switch on x86.

This option indicates that the thread uses the x86 CPU's floating point and SSE registers. This instructs the kernel to take additional steps to save and restore the contents of these registers when scheduling the thread. No effect if

CONFIG_X86_SSE 

is not enabled.

◆ k_thread_access_grant

#define k_thread_access_grant (   thread,
  ... 
)     FOR_EACH_FIXED_ARG(k_object_access_grant, (;), (thread), __VA_ARGS__)

#include <include/zephyr/kernel.h>

Grant a thread access to a set of kernel objects.

This is a convenience function. For the provided thread, grant access to the remaining arguments, which must be pointers to kernel objects.

The thread object must be initialized (i.e. running). The objects don't need to be. Note that NULL shouldn't be passed as an argument.

Parameters
threadThread to grant access to objects
...list of kernel object pointers

◆ K_THREAD_DEFINE

#define K_THREAD_DEFINE (   name,
  stack_size,
  entry,
  p1,
  p2,
  p3,
  prio,
  options,
  delay 
)

#include <include/zephyr/kernel.h>

Value:
K_THREAD_STACK_DEFINE(_k_thread_stack_##name, stack_size); \
Z_THREAD_COMMON_DEFINE(name, stack_size, entry, p1, p2, p3, \
prio, options, delay)
#define K_THREAD_STACK_DEFINE(sym, size)
Define a toplevel thread stack memory region.
Definition thread_stack.h:516

Statically define and initialize a thread.

The thread may be scheduled for immediate execution or a delayed start.

Thread options are architecture-specific, and can include K_ESSENTIAL, K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating them using "|" (the logical OR operator).

The ID of the thread can be accessed using:

extern const k_tid_t <name>;
Parameters
nameName of the thread.
stack_sizeStack size in bytes.
entryThread entry function.
p11st entry point parameter.
p22nd entry point parameter.
p33rd entry point parameter.
prioThread priority.
optionsThread options.
delayScheduling delay (in milliseconds), zero for no delay.
Note
Static threads with zero delay should not normally have MetaIRQ priority levels. This can preempt the system initialization handling (depending on the priority of the main thread) and cause surprising ordering side effects. It will not affect anything in the OS per se, but consider it bad practice. Use a SYS_INIT() callback if you need to run code before entrance to the application main().

◆ K_USER

#define K_USER   (BIT(2))

#include <include/zephyr/kernel.h>

user mode thread

This thread has dropped from supervisor mode to user mode and consequently has additional restrictions

Typedef Documentation

◆ k_thread_user_cb_t

typedef void(* k_thread_user_cb_t) (const struct k_thread *thread, void *user_data)

Function Documentation

◆ k_busy_wait()

void k_busy_wait ( uint32_t  usec_to_wait)

#include <include/zephyr/kernel.h>

Cause the current thread to busy wait.

This routine causes the current thread to execute a "do nothing" loop for usec_to_wait microseconds.

Note
The clock used for the microsecond-resolution delay here may be skewed relative to the clock used for system timeouts like k_sleep(). For example k_busy_wait(1000) may take slightly more or less time than k_sleep(K_MSEC(1)), with the offset dependent on clock tolerances.
In case when
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE 
and
CONFIG_PM 
options are enabled, this function may not work. The timer/clock used for delay processing may be disabled/inactive.

◆ k_can_yield()

bool k_can_yield ( void  )

#include <include/zephyr/kernel.h>

Check whether it is possible to yield in the current context.

This routine checks whether the kernel is in a state where it is possible to yield or call blocking API's. It should be used by code that needs to yield to perform correctly, but can feasibly be called from contexts where that is not possible. For example in the PRE_KERNEL initialization step, or when being run from the idle thread.

Returns
True if it is possible to yield in the current context, false otherwise.

◆ k_current_get()

static __attribute_const__ k_tid_t k_current_get ( void  )
inlinestatic

#include <include/zephyr/kernel.h>

Get thread ID of the current thread.

Returns
ID of current thread.

◆ k_msleep()

static int32_t k_msleep ( int32_t  ms)
inlinestatic

#include <include/zephyr/kernel.h>

Put the current thread to sleep.

This routine puts the current thread to sleep for duration milliseconds.

Parameters
msNumber of milliseconds to sleep.
Returns
Zero if the requested time has elapsed or if the thread was woken up by the k_wakeup call, the time left to sleep rounded up to the nearest millisecond.

◆ k_sched_current_thread_query()

__attribute_const__ k_tid_t k_sched_current_thread_query ( void  )

#include <include/zephyr/kernel.h>

Query thread ID of the current thread.

This unconditionally queries the kernel via a system call.

Note
Use k_current_get() unless absolutely sure this is necessary. This should only be used directly where the thread local variable cannot be used or may contain invalid values if thread local storage (TLS) is enabled. If TLS is not enabled, this is the same as k_current_get().
Returns
ID of current thread.

◆ k_sched_lock()

void k_sched_lock ( void  )

#include <include/zephyr/kernel.h>

Lock the scheduler.

This routine prevents the current thread from being preempted by another thread by instructing the scheduler to treat it as a cooperative thread. If the thread subsequently performs an operation that makes it unready, it will be context switched out in the normal manner. When the thread again becomes the current thread, its non-preemptible status is maintained.

This routine can be called recursively.

Owing to clever implementation details, scheduler locks are extremely fast for non-userspace threads (just one byte inc/decrement in the thread struct).

Note
This works by elevating the thread priority temporarily to a cooperative priority, allowing cheap synchronization vs. other preemptible or cooperative threads running on the current CPU. It does not prevent preemption or asynchrony of other types. It does not prevent threads from running on other CPUs when CONFIG_SMP=y. It does not prevent interrupts from happening, nor does it prevent threads with MetaIRQ priorities from preempting the current thread. In general this is a historical API not well-suited to modern applications, use with care.

◆ k_sched_time_slice_set()

void k_sched_time_slice_set ( int32_t  slice,
int  prio 
)

#include <include/zephyr/kernel.h>

Set time-slicing period and scope.

This routine specifies how the scheduler will perform time slicing of preemptible threads.

To enable time slicing, slice must be non-zero. The scheduler ensures that no thread runs for more than the specified time limit before other threads of that priority are given a chance to execute. Any thread whose priority is higher than prio is exempted, and may execute as long as desired without being preempted due to time slicing.

Time slicing only limits the maximum amount of time a thread may continuously execute. Once the scheduler selects a thread for execution, there is no minimum guaranteed time the thread will execute before threads of greater or equal priority are scheduled.

When the current thread is the only one of that priority eligible for execution, this routine has no effect; the thread is immediately rescheduled after the slice period expires.

To disable timeslicing, set both slice and prio to zero.

Parameters
sliceMaximum time slice length (in milliseconds).
prioHighest thread priority level eligible for time slicing.

◆ k_sched_unlock()

void k_sched_unlock ( void  )

#include <include/zephyr/kernel.h>

Unlock the scheduler.

This routine reverses the effect of a previous call to k_sched_lock(). A thread must call the routine once for each time it called k_sched_lock() before the thread becomes preemptible.

◆ k_sleep()

int32_t k_sleep ( k_timeout_t  timeout)

#include <include/zephyr/kernel.h>

Put the current thread to sleep.

This routine puts the current thread to sleep for duration, specified as a k_timeout_t object.

Note
if timeout is set to K_FOREVER then the thread is suspended.
Parameters
timeoutDesired duration of sleep.
Returns
Zero if the requested time has elapsed or if the thread was woken up by the k_wakeup call, the time left to sleep rounded up to the nearest millisecond.

◆ k_thread_abort()

void k_thread_abort ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Abort a thread.

This routine permanently stops execution of thread. The thread is taken off all kernel queues it is part of (i.e. the ready queue, the timeout queue, or a kernel object wait queue). However, any kernel resources the thread might currently own (such as mutexes or memory blocks) are not released. It is the responsibility of the caller of this routine to ensure all necessary cleanup is performed.

After k_thread_abort() returns, the thread is guaranteed not to be running or to become runnable anywhere on the system. Normally this is done via blocking the caller (in the same manner as k_thread_join()), but in interrupt context on SMP systems the implementation is required to spin for threads that are running on other CPUs.

Parameters
threadID of thread to abort.

◆ k_thread_cpu_mask_clear()

int k_thread_cpu_mask_clear ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Sets all CPU enable masks to zero.

After this returns, the thread will no longer be schedulable on any CPUs. The thread must not be currently runnable.

Note
You should enable
CONFIG_SCHED_CPU_MASK 
in your project configuration.
Parameters
threadThread to operate upon
Returns
Zero on success, otherwise error code

◆ k_thread_cpu_mask_disable()

int k_thread_cpu_mask_disable ( k_tid_t  thread,
int  cpu 
)

#include <include/zephyr/kernel.h>

Prevent thread to run on specified CPU.

The thread must not be currently runnable.

Note
You should enable
CONFIG_SCHED_CPU_MASK 
in your project configuration.
Parameters
threadThread to operate upon
cpuCPU index
Returns
Zero on success, otherwise error code

◆ k_thread_cpu_mask_enable()

int k_thread_cpu_mask_enable ( k_tid_t  thread,
int  cpu 
)

#include <include/zephyr/kernel.h>

Enable thread to run on specified CPU.

The thread must not be currently runnable.

Note
You should enable
CONFIG_SCHED_CPU_MASK 
in your project configuration.
Parameters
threadThread to operate upon
cpuCPU index
Returns
Zero on success, otherwise error code

◆ k_thread_cpu_mask_enable_all()

int k_thread_cpu_mask_enable_all ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Sets all CPU enable masks to one.

After this returns, the thread will be schedulable on any CPU. The thread must not be currently runnable.

Note
You should enable
CONFIG_SCHED_CPU_MASK 
in your project configuration.
Parameters
threadThread to operate upon
Returns
Zero on success, otherwise error code

◆ k_thread_cpu_pin()

int k_thread_cpu_pin ( k_tid_t  thread,
int  cpu 
)

#include <include/zephyr/kernel.h>

Pin a thread to a CPU.

Pin a thread to a CPU by first clearing the cpu mask and then enabling the thread on the selected CPU.

Parameters
threadThread to operate upon
cpuCPU index
Returns
Zero on success, otherwise error code

◆ k_thread_create()

k_tid_t k_thread_create ( struct k_thread new_thread,
k_thread_stack_t stack,
size_t  stack_size,
k_thread_entry_t  entry,
void *  p1,
void *  p2,
void *  p3,
int  prio,
uint32_t  options,
k_timeout_t  delay 
)

#include <include/zephyr/kernel.h>

Create a thread.

This routine initializes a thread, then schedules it for execution.

The new thread may be scheduled for immediate execution or a delayed start. If the newly spawned thread does not have a delayed start the kernel scheduler may preempt the current thread to allow the new thread to execute.

Thread options are architecture-specific, and can include K_ESSENTIAL, K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating them using "|" (the logical OR operator).

Stack objects passed to this function must be originally defined with either of these macros in order to be portable:

  • K_THREAD_STACK_DEFINE() - For stacks that may support either user or supervisor threads.
  • K_KERNEL_STACK_DEFINE() - For stacks that may support supervisor threads only. These stacks use less memory if CONFIG_USERSPACE is enabled.

The stack_size parameter has constraints. It must either be:

Using other values, or sizeof(stack) may produce undefined behavior.

Parameters
new_threadPointer to uninitialized struct k_thread
stackPointer to the stack space.
stack_sizeStack size in bytes.
entryThread entry function.
p11st entry point parameter.
p22nd entry point parameter.
p33rd entry point parameter.
prioThread priority.
optionsThread options.
delayScheduling delay, or K_NO_WAIT (for no delay).
Returns
ID of new thread.

◆ k_thread_custom_data_get()

void * k_thread_custom_data_get ( void  )

#include <include/zephyr/kernel.h>

Get current thread's custom data.

This routine returns the custom data for the current thread.

Returns
Current custom data value.

◆ k_thread_custom_data_set()

void k_thread_custom_data_set ( void *  value)

#include <include/zephyr/kernel.h>

Set current thread's custom data.

This routine sets the custom data for the current thread to @ value.

Custom data is not used by the kernel itself, and is freely available for a thread to use as it sees fit. It can be used as a framework upon which to build thread-local storage.

Parameters
valueNew custom data value.

◆ k_thread_deadline_set()

void k_thread_deadline_set ( k_tid_t  thread,
int  deadline 
)

#include <include/zephyr/kernel.h>

Set deadline expiration time for scheduler.

This sets the "deadline" expiration as a time delta from the current time, in the same units used by k_cycle_get_32(). The scheduler (when deadline scheduling is enabled) will choose the next expiring thread when selecting between threads at the same static priority. Threads at different priorities will be scheduled according to their static priority.

Note
Deadlines are stored internally using 32 bit unsigned integers. The number of cycles between the "first" deadline in the scheduler queue and the "last" deadline must be less than 2^31 (i.e a signed non-negative quantity). Failure to adhere to this rule may result in scheduled threads running in an incorrect deadline order.
Despite the API naming, the scheduler makes no guarantees the thread WILL be scheduled within that deadline, nor does it take extra metadata (like e.g. the "runtime" and "period" parameters in Linux sched_setattr()) that allows the kernel to validate the scheduling for achievability. Such features could be implemented above this call, which is simply input to the priority selection logic.
You should enable
CONFIG_SCHED_DEADLINE 
in your project configuration.
Parameters
threadA thread on which to set the deadline
deadlineA time delta, in cycle units

◆ k_thread_foreach()

void k_thread_foreach ( k_thread_user_cb_t  user_cb,
void *  user_data 
)

#include <include/zephyr/kernel.h>

Iterate over all the threads in the system.

This routine iterates over all the threads in the system and calls the user_cb function for each thread.

Parameters
user_cbPointer to the user callback function.
user_dataPointer to user data.
Note
CONFIG_THREAD_MONITOR 
must be set for this function to be effective.
This API uses k_spin_lock to protect the _kernel.threads list which means creation of new threads and terminations of existing threads are blocked until this API returns.

◆ k_thread_foreach_filter_by_cpu()

void k_thread_foreach_filter_by_cpu ( unsigned int  cpu,
k_thread_user_cb_t  user_cb,
void *  user_data 
)

#include <include/zephyr/kernel.h>

Iterate over all the threads in running on specified cpu.

This function is does otherwise the same thing as k_thread_foreach(), but it only loops through the threads running on specified cpu only. If CONFIG_SMP is not defined the implementation this is the same as k_thread_foreach(), with an assert cpu == 0.

Parameters
cpuThe filtered cpu number
user_cbPointer to the user callback function.
user_dataPointer to user data.
Note
CONFIG_THREAD_MONITOR 
must be set for this function to be effective.
This API uses k_spin_lock to protect the _kernel.threads list which means creation of new threads and terminations of existing threads are blocked until this API returns.

◆ k_thread_foreach_unlocked()

void k_thread_foreach_unlocked ( k_thread_user_cb_t  user_cb,
void *  user_data 
)

#include <include/zephyr/kernel.h>

Iterate over all the threads in the system without locking.

This routine works exactly the same like k_thread_foreach but unlocks interrupts when user_cb is executed.

Parameters
user_cbPointer to the user callback function.
user_dataPointer to user data.
Note
CONFIG_THREAD_MONITOR 
must be set for this function to be effective.
This API uses k_spin_lock only when accessing the _kernel.threads queue elements. It unlocks it during user callback function processing. If a new task is created when this foreach function is in progress, the added new task would not be included in the enumeration. If a task is aborted during this enumeration, there would be a race here and there is a possibility that this aborted task would be included in the enumeration.
If the task is aborted and the memory occupied by its k_thread structure is reused when this k_thread_foreach_unlocked is in progress it might even lead to the system behave unstable. This function may never return, as it would follow some next task pointers treating given pointer as a pointer to the k_thread structure while it is something different right now. Do not reuse the memory that was occupied by k_thread structure of aborted task if it was aborted after this function was called in any context.

◆ k_thread_foreach_unlocked_filter_by_cpu()

void k_thread_foreach_unlocked_filter_by_cpu ( unsigned int  cpu,
k_thread_user_cb_t  user_cb,
void *  user_data 
)

#include <include/zephyr/kernel.h>

Iterate over the threads in running on current cpu without locking.

This function does otherwise the same thing as k_thread_foreach_unlocked(), but it only loops through the threads running on specified cpu. If CONFIG_SMP is not defined the implementation this is the same as k_thread_foreach_unlocked(), with an assert requiring cpu == 0.

Parameters
cpuThe filtered cpu number
user_cbPointer to the user callback function.
user_dataPointer to user data.
Note
CONFIG_THREAD_MONITOR 
must be set for this function to be effective.
This API uses k_spin_lock only when accessing the _kernel.threads queue elements. It unlocks it during user callback function processing. If a new task is created when this foreach function is in progress, the added new task would not be included in the enumeration. If a task is aborted during this enumeration, there would be a race here and there is a possibility that this aborted task would be included in the enumeration.
If the task is aborted and the memory occupied by its k_thread structure is reused when this k_thread_foreach_unlocked is in progress it might even lead to the system behave unstable. This function may never return, as it would follow some next task pointers treating given pointer as a pointer to the k_thread structure while it is something different right now. Do not reuse the memory that was occupied by k_thread structure of aborted task if it was aborted after this function was called in any context.

◆ k_thread_heap_assign()

static void k_thread_heap_assign ( struct k_thread thread,
struct k_heap heap 
)
inlinestatic

#include <include/zephyr/kernel.h>

Assign a resource memory pool to a thread.

By default, threads have no resource pool assigned unless their parent thread has a resource pool, in which case it is inherited. Multiple threads may be assigned to the same memory pool.

Changing a thread's resource pool will not migrate allocations from the previous pool.

Parameters
threadTarget thread to assign a memory pool for resource requests.
heapHeap object to use for resources, or NULL if the thread should no longer have a memory pool.

◆ k_thread_join()

int k_thread_join ( struct k_thread thread,
k_timeout_t  timeout 
)

#include <include/zephyr/kernel.h>

Sleep until a thread exits.

The caller will be put to sleep until the target thread exits, either due to being aborted, self-exiting, or taking a fatal error. This API returns immediately if the thread isn't running.

This API may only be called from ISRs with a K_NO_WAIT timeout, where it can be useful as a predicate to detect when a thread has aborted.

Parameters
threadThread to wait to exit
timeoutupper bound time to wait for the thread to exit.
Return values
0success, target thread has exited or wasn't running
-EBUSYreturned without waiting
-EAGAINwaiting period timed out
-EDEADLKtarget thread is joining on the caller, or target thread is the caller

◆ k_thread_name_copy()

int k_thread_name_copy ( k_tid_t  thread,
char *  buf,
size_t  size 
)

#include <include/zephyr/kernel.h>

Copy the thread name into a supplied buffer.

Parameters
threadThread to obtain name information
bufDestination buffer
sizeDestination buffer size
Return values
-ENOSPCDestination buffer too small
-EFAULTMemory access error
-ENOSYSThread name feature not enabled
0Success

◆ k_thread_name_get()

const char * k_thread_name_get ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Get thread name.

Get the name of a thread

Parameters
threadThread ID
Return values
Threadname, or NULL if configuration not enabled

◆ k_thread_name_set()

int k_thread_name_set ( k_tid_t  thread,
const char *  str 
)

#include <include/zephyr/kernel.h>

Set current thread name.

Set the name of the thread to be used when

CONFIG_THREAD_MONITOR 

is enabled for tracing and debugging.

Parameters
threadThread to set name, or NULL to set the current thread
strName string
Return values
0on success
-EFAULTMemory access error with supplied string
-ENOSYSThread name configuration option not enabled
-EINVALThread name too long

◆ k_thread_priority_get()

int k_thread_priority_get ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Get a thread's priority.

This routine gets the priority of thread.

Parameters
threadID of thread whose priority is needed.
Returns
Priority of thread.

◆ k_thread_priority_set()

void k_thread_priority_set ( k_tid_t  thread,
int  prio 
)

#include <include/zephyr/kernel.h>

Set a thread's priority.

This routine immediately changes the priority of thread.

Rescheduling can occur immediately depending on the priority thread is set to:

  • If its priority is raised above the priority of a currently scheduled preemptible thread, thread will be scheduled in.
  • If the caller lowers the priority of a currently scheduled preemptible thread below that of other threads in the system, the thread of the highest priority will be scheduled in.

Priority can be assigned in the range of -CONFIG_NUM_COOP_PRIORITIES to CONFIG_NUM_PREEMPT_PRIORITIES-1, where -CONFIG_NUM_COOP_PRIORITIES is the highest priority.

Parameters
threadID of thread whose priority is to be set.
prioNew priority.
Warning
Changing the priority of a thread currently involved in mutex priority inheritance may result in undefined behavior.

◆ k_thread_resume()

void k_thread_resume ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Resume a suspended thread.

This routine allows the kernel scheduler to make thread the current thread, when it is next eligible for that role.

If thread is not currently suspended, the routine has no effect.

Parameters
threadID of thread to resume.

◆ k_thread_stack_alloc()

k_thread_stack_t * k_thread_stack_alloc ( size_t  size,
int  flags 
)

#include <include/zephyr/kernel.h>

Dynamically allocate a thread stack.

Relevant stack creation flags include:

  • K_USER allocate a userspace thread (requires CONFIG_USERSPACE=y)
Parameters
sizeStack size in bytes.
flagsStack creation flags, or 0.
Return values
theallocated thread stack on success.
NULLon failure.
See also
CONFIG_DYNAMIC_THREAD

◆ k_thread_stack_free()

int k_thread_stack_free ( k_thread_stack_t stack)

#include <include/zephyr/kernel.h>

Free a dynamically allocated thread stack.

Parameters
stackPointer to the thread stack.
Return values
0on success.
-EBUSYif the thread stack is in use.
-EINVALif stack is invalid.
-ENOSYSif dynamic thread stack allocation is disabled
See also
CONFIG_DYNAMIC_THREAD

◆ k_thread_start()

void k_thread_start ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Start an inactive thread.

If a thread was created with K_FOREVER in the delay parameter, it will not be added to the scheduling queue until this function is called on it.

Parameters
threadthread to start

◆ k_thread_state_str()

const char * k_thread_state_str ( k_tid_t  thread_id,
char *  buf,
size_t  buf_size 
)

#include <include/zephyr/kernel.h>

Get thread state string.

This routine generates a human friendly string containing the thread's state, and copies as much of it as possible into buf.

Parameters
thread_idThread ID
bufBuffer into which to copy state strings
buf_sizeSize of the buffer
Return values
Pointerto buf if data was copied, else a pointer to "".

◆ k_thread_suspend()

void k_thread_suspend ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Suspend a thread.

This routine prevents the kernel scheduler from making thread the current thread. All other internal operations on thread are still performed; for example, kernel objects it is waiting on are still handed to it. Note that any existing timeouts (e.g. k_sleep(), or a timeout argument to k_sem_take() et. al.) will be canceled. On resume, the thread will begin running immediately and return from the blocked call.

When the target thread is active on another CPU, the caller will block until the target thread is halted (suspended or aborted). But if the caller is in an interrupt context, it will spin waiting for that target thread active on another CPU to halt.

If thread is already suspended, the routine has no effect.

Parameters
threadID of thread to suspend.

◆ k_thread_time_slice_set()

void k_thread_time_slice_set ( struct k_thread th,
int32_t  slice_ticks,
k_thread_timeslice_fn_t  expired,
void *  data 
)

#include <include/zephyr/kernel.h>

Set thread time slice.

As for k_sched_time_slice_set, but (when CONFIG_TIMESLICE_PER_THREAD=y) sets the timeslice for a specific thread. When non-zero, this timeslice will take precedence over the global value.

When such a thread's timeslice expires, the configured callback will be called before the thread is removed/re-added to the run queue. This callback will occur in interrupt context, and the specified thread is guaranteed to have been preempted by the currently-executing ISR. Such a callback is free to, for example, modify the thread priority or slice time for future execution, suspend the thread, etc...

Note
Unlike the older API, the time slice parameter here is specified in ticks, not milliseconds. Ticks have always been the internal unit, and not all platforms have integer conversions between the two.
Threads with a non-zero slice time set will be timesliced always, even if they are higher priority than the maximum timeslice priority set via k_sched_time_slice_set().
The callback notification for slice expiration happens, as it must, while the thread is still "current", and thus it happens before any registered timeouts at this tick. This has the somewhat confusing side effect that the tick time (c.f. k_uptime_get()) does not yet reflect the expired ticks. Applications wishing to make fine-grained timing decisions within this callback should use the cycle API, or derived facilities like k_thread_runtime_stats_get().
Parameters
thA valid, initialized thread
slice_ticksMaximum timeslice, in ticks
expiredCallback function called on slice expiration
dataParameter for the expiration handler

◆ k_thread_timeout_expires_ticks()

k_ticks_t k_thread_timeout_expires_ticks ( const struct k_thread thread)

#include <include/zephyr/kernel.h>

Get time when a thread wakes up, in system ticks.

This routine computes the system uptime when a waiting thread next executes, in units of system ticks. If the thread is not waiting, it returns current system time.

◆ k_thread_timeout_remaining_ticks()

k_ticks_t k_thread_timeout_remaining_ticks ( const struct k_thread thread)

#include <include/zephyr/kernel.h>

Get time remaining before a thread wakes up, in system ticks.

This routine computes the time remaining before a waiting thread next executes, in units of system ticks. If the thread is not waiting, it returns zero.

◆ k_thread_user_mode_enter()

FUNC_NORETURN void k_thread_user_mode_enter ( k_thread_entry_t  entry,
void *  p1,
void *  p2,
void *  p3 
)

#include <include/zephyr/kernel.h>

Drop a thread's privileges permanently to user mode.

This allows a supervisor thread to be re-used as a user thread. This function does not return, but control will transfer to the provided entry point as if this was a new user thread.

The implementation ensures that the stack buffer contents are erased. Any thread-local storage will be reverted to a pristine state.

Memory domain membership, resource pool assignment, kernel object permissions, priority, and thread options are preserved.

A common use of this function is to re-use the main thread as a user thread once all supervisor mode-only tasks have been completed.

Parameters
entryFunction to start executing from
p11st entry point parameter
p22nd entry point parameter
p33rd entry point parameter

◆ k_usleep()

int32_t k_usleep ( int32_t  us)

#include <include/zephyr/kernel.h>

Put the current thread to sleep with microsecond resolution.

This function is unlikely to work as expected without kernel tuning. In particular, because the lower bound on the duration of a sleep is the duration of a tick,

CONFIG_SYS_CLOCK_TICKS_PER_SEC 

must be adjusted to achieve the resolution desired. The implications of doing this must be understood before attempting to use k_usleep(). Use with caution.

Parameters
usNumber of microseconds to sleep.
Returns
Zero if the requested time has elapsed or if the thread was woken up by the k_wakeup call, the time left to sleep rounded up to the nearest microsecond.

◆ k_wakeup()

void k_wakeup ( k_tid_t  thread)

#include <include/zephyr/kernel.h>

Wake up a sleeping thread.

This routine prematurely wakes up thread from sleeping.

If thread is not currently sleeping, the routine has no effect.

Parameters
threadID of thread to wake.

◆ k_yield()

void k_yield ( void  )

#include <include/zephyr/kernel.h>

Yield the current thread.

This routine causes the current thread to yield execution to another thread of the same or higher priority. If there are no other ready threads of the same or higher priority, the routine returns immediately.