diff --git a/core/include/thread.h b/core/include/thread.h index 8ec569a5f9..9325e90eaa 100644 --- a/core/include/thread.h +++ b/core/include/thread.h @@ -79,6 +79,16 @@ kernel_pid_t thread_create(char *stack, void *(*function)(void *arg), void *arg, const char *name); + +/** + * @brief Retreive a thread control block by PID. + * @details This is a bound-checked variant of accessing `sched_threads[pid]` directly. + * If you know that the PID is valid, then don't use this function. + * @param[in] pid Thread to retreive. + * @return `NULL` if the PID is invalid or there is no such thread. + */ +volatile tcb_t *thread_get(kernel_pid_t pid); + /** * @brief Returns the status of a process * diff --git a/core/thread.c b/core/thread.c index 1fe535fdca..4d30e35069 100644 --- a/core/thread.c +++ b/core/thread.c @@ -37,22 +37,24 @@ inline kernel_pid_t thread_getpid(void) return sched_active_thread->pid; } +volatile tcb_t *thread_get(kernel_pid_t pid) +{ + if ((pid != KERNEL_PID_UNDEF) && (0 <= pid) && (pid < MAXTHREADS)) { + return sched_threads[pid]; + } + return NULL; +} + int thread_getstatus(kernel_pid_t pid) { - if (sched_threads[pid] == NULL) { - return STATUS_NOT_FOUND; - } - - return sched_threads[pid]->status; + volatile tcb_t *t = thread_get(pid); + return t ? t->status : STATUS_NOT_FOUND; } const char *thread_getname(kernel_pid_t pid) { - if (sched_threads[pid] == NULL) { - return NULL; - } - - return sched_threads[pid]->name; + volatile tcb_t *t = thread_get(pid); + return t ? t->name : NULL; } void thread_sleep(void)