thread.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2006-03-28 Bernard first version
  9. * 2006-04-29 Bernard implement thread timer
  10. * 2006-04-30 Bernard added THREAD_DEBUG
  11. * 2006-05-27 Bernard fixed the rt_thread_yield bug
  12. * 2006-06-03 Bernard fixed the thread timer init bug
  13. * 2006-08-10 Bernard fixed the timer bug in thread_sleep
  14. * 2006-09-03 Bernard changed rt_timer_delete to rt_timer_detach
  15. * 2006-09-03 Bernard implement rt_thread_detach
  16. * 2008-02-16 Bernard fixed the rt_thread_timeout bug
  17. * 2010-03-21 Bernard change the errno of rt_thread_delay/sleep to
  18. * RT_EOK.
  19. * 2010-11-10 Bernard add cleanup callback function in thread exit.
  20. * 2011-09-01 Bernard fixed rt_thread_exit issue when the current
  21. * thread preempted, which reported by Jiaxing Lee.
  22. * 2011-09-08 Bernard fixed the scheduling issue in rt_thread_startup.
  23. * 2012-12-29 Bernard fixed compiling warning.
  24. * 2016-08-09 ArdaFu add thread suspend and resume hook.
  25. * 2017-04-10 armink fixed the rt_thread_delete and rt_thread_detach
  26. * bug when thread has not startup.
  27. * 2018-11-22 Jesven yield is same to rt_schedule
  28. * add support for tasks bound to cpu
  29. * 2021-02-24 Meco Man rearrange rt_thread_control() - schedule the thread when close it
  30. * 2021-11-15 THEWON Remove duplicate work between idle and _thread_exit
  31. * 2021-12-27 Meco Man remove .init_priority
  32. * 2022-01-07 Gabriel Moving __on_rt_xxxxx_hook to thread.c
  33. * 2022-01-24 THEWON let _thread_sleep return thread->error when using signal
  34. * 2022-10-15 Bernard add nested mutex feature
  35. * 2023-09-15 xqyjlj perf rt_hw_interrupt_disable/enable
  36. * 2023-12-10 xqyjlj fix thread_exit/detach/delete
  37. * fix rt_thread_delay
  38. */
  39. #include <rthw.h>
  40. #include <rtthread.h>
  41. #include <stddef.h>
  42. #define DBG_TAG "kernel.thread"
  43. #define DBG_LVL DBG_INFO
  44. #include <rtdbg.h>
  45. #if defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR)
  46. static void (*rt_thread_suspend_hook)(rt_thread_t thread);
  47. static void (*rt_thread_resume_hook) (rt_thread_t thread);
  48. /**
  49. * @brief This function sets a hook function when the system suspend a thread.
  50. *
  51. * @note The hook function must be simple and never be blocked or suspend.
  52. *
  53. * @param hook is the specified hook function.
  54. */
  55. void rt_thread_suspend_sethook(void (*hook)(rt_thread_t thread))
  56. {
  57. rt_thread_suspend_hook = hook;
  58. }
  59. /**
  60. * @brief This function sets a hook function when the system resume a thread.
  61. *
  62. * @note The hook function must be simple and never be blocked or suspend.
  63. *
  64. * @param hook is the specified hook function.
  65. */
  66. void rt_thread_resume_sethook(void (*hook)(rt_thread_t thread))
  67. {
  68. rt_thread_resume_hook = hook;
  69. }
  70. RT_OBJECT_HOOKLIST_DEFINE(rt_thread_inited);
  71. #endif /* defined(RT_USING_HOOK) && defined(RT_HOOK_USING_FUNC_PTR) */
  72. #ifdef RT_USING_MUTEX
  73. static void _thread_detach_from_mutex(rt_thread_t thread)
  74. {
  75. rt_list_t *node;
  76. rt_list_t *tmp_list;
  77. struct rt_mutex *mutex;
  78. rt_base_t level;
  79. level = rt_spin_lock_irqsave(&thread->spinlock);
  80. /* check if thread is waiting on a mutex */
  81. if ((thread->pending_object) &&
  82. (rt_object_get_type(thread->pending_object) == RT_Object_Class_Mutex))
  83. {
  84. /* remove it from its waiting list */
  85. struct rt_mutex *mutex = (struct rt_mutex*)thread->pending_object;
  86. rt_mutex_drop_thread(mutex, thread);
  87. thread->pending_object = RT_NULL;
  88. }
  89. /* free taken mutex after detaching from waiting, so we don't lost mutex just got */
  90. rt_list_for_each_safe(node, tmp_list, &(thread->taken_object_list))
  91. {
  92. mutex = rt_list_entry(node, struct rt_mutex, taken_list);
  93. LOG_D("Thread [%s] exits while holding mutex [%s].\n", thread->parent.name, mutex->parent.parent.name);
  94. /* recursively take */
  95. mutex->hold = 1;
  96. rt_mutex_release(mutex);
  97. }
  98. rt_spin_unlock_irqrestore(&thread->spinlock, level);
  99. }
  100. #else
  101. static void _thread_detach_from_mutex(rt_thread_t thread) {}
  102. #endif
  103. static void _thread_exit(void)
  104. {
  105. struct rt_thread *thread;
  106. rt_base_t critical_level;
  107. /* get current thread */
  108. thread = rt_thread_self();
  109. critical_level = rt_enter_critical();
  110. rt_thread_close(thread);
  111. _thread_detach_from_mutex(thread);
  112. /* insert to defunct thread list */
  113. rt_thread_defunct_enqueue(thread);
  114. rt_exit_critical_safe(critical_level);
  115. /* switch to next task */
  116. rt_schedule();
  117. }
  118. /**
  119. * @brief This function is the timeout function for thread, normally which is invoked
  120. * when thread is timeout to wait some resource.
  121. *
  122. * @param parameter is the parameter of thread timeout function
  123. */
  124. static void _thread_timeout(void *parameter)
  125. {
  126. struct rt_thread *thread;
  127. rt_sched_lock_level_t slvl;
  128. thread = (struct rt_thread *)parameter;
  129. /* parameter check */
  130. RT_ASSERT(thread != RT_NULL);
  131. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  132. rt_sched_lock(&slvl);
  133. /**
  134. * resume of the thread and stop of the thread timer should be an atomic
  135. * operation. So we don't expected that thread had resumed.
  136. */
  137. RT_ASSERT(rt_sched_thread_is_suspended(thread));
  138. /* set error number */
  139. thread->error = -RT_ETIMEOUT;
  140. /* remove from suspend list */
  141. rt_list_remove(&RT_THREAD_LIST_NODE(thread));
  142. /* insert to schedule ready list */
  143. rt_sched_insert_thread(thread);
  144. /* do schedule and release the scheduler lock */
  145. rt_sched_unlock_n_resched(slvl);
  146. }
  147. static rt_err_t _thread_init(struct rt_thread *thread,
  148. const char *name,
  149. void (*entry)(void *parameter),
  150. void *parameter,
  151. void *stack_start,
  152. rt_uint32_t stack_size,
  153. rt_uint8_t priority,
  154. rt_uint32_t tick)
  155. {
  156. RT_UNUSED(name);
  157. rt_sched_thread_init_ctx(thread, tick, priority);
  158. #ifdef RT_USING_MEM_PROTECTION
  159. thread->mem_regions = RT_NULL;
  160. #endif
  161. #ifdef RT_USING_SMART
  162. thread->wakeup_handle.func = RT_NULL;
  163. #endif
  164. thread->entry = (void *)entry;
  165. thread->parameter = parameter;
  166. /* stack init */
  167. thread->stack_addr = stack_start;
  168. thread->stack_size = stack_size;
  169. /* init thread stack */
  170. rt_memset(thread->stack_addr, '#', thread->stack_size);
  171. #ifdef RT_USING_HW_STACK_GUARD
  172. rt_hw_stack_guard_init(thread);
  173. #endif
  174. #ifdef ARCH_CPU_STACK_GROWS_UPWARD
  175. thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter,
  176. (void *)((char *)thread->stack_addr),
  177. (void *)_thread_exit);
  178. #else
  179. thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter,
  180. (rt_uint8_t *)((char *)thread->stack_addr + thread->stack_size - sizeof(rt_ubase_t)),
  181. (void *)_thread_exit);
  182. #endif /* ARCH_CPU_STACK_GROWS_UPWARD */
  183. #ifdef RT_USING_MUTEX
  184. rt_list_init(&thread->taken_object_list);
  185. thread->pending_object = RT_NULL;
  186. #endif
  187. #ifdef RT_USING_EVENT
  188. thread->event_set = 0;
  189. thread->event_info = 0;
  190. #endif /* RT_USING_EVENT */
  191. /* error and flags */
  192. thread->error = RT_EOK;
  193. /* lock init */
  194. #ifdef RT_USING_SMP
  195. rt_atomic_store(&thread->cpus_lock_nest, 0);
  196. #endif
  197. /* initialize cleanup function and user data */
  198. thread->cleanup = 0;
  199. thread->user_data = 0;
  200. /* initialize thread timer */
  201. rt_timer_init(&(thread->thread_timer),
  202. thread->parent.name,
  203. _thread_timeout,
  204. thread,
  205. 0,
  206. RT_TIMER_FLAG_ONE_SHOT | RT_TIMER_FLAG_THREAD_TIMER);
  207. /* initialize signal */
  208. #ifdef RT_USING_SIGNALS
  209. thread->sig_mask = 0x00;
  210. thread->sig_pending = 0x00;
  211. #ifndef RT_USING_SMP
  212. thread->sig_ret = RT_NULL;
  213. #endif /* RT_USING_SMP */
  214. thread->sig_vectors = RT_NULL;
  215. thread->si_list = RT_NULL;
  216. #endif /* RT_USING_SIGNALS */
  217. #ifdef RT_USING_SMART
  218. thread->tid_ref_count = 0;
  219. thread->lwp = RT_NULL;
  220. thread->susp_recycler = RT_NULL;
  221. thread->robust_list = RT_NULL;
  222. rt_list_init(&(thread->sibling));
  223. /* lwp thread-signal init */
  224. rt_memset(&thread->signal.sigset_mask, 0, sizeof(lwp_sigset_t));
  225. rt_memset(&thread->signal.sig_queue.sigset_pending, 0, sizeof(lwp_sigset_t));
  226. rt_list_init(&thread->signal.sig_queue.siginfo_list);
  227. rt_memset(&thread->user_ctx, 0, sizeof thread->user_ctx);
  228. /* initialize user_time and system_time */
  229. thread->user_time = 0;
  230. thread->system_time = 0;
  231. #endif
  232. #ifdef RT_USING_CPU_USAGE_TRACER
  233. thread->user_time = 0;
  234. thread->system_time = 0;
  235. thread->total_time_prev = 0;
  236. thread->cpu_usage = 0;
  237. #endif /* RT_USING_CPU_USAGE_TRACER */
  238. #ifdef RT_USING_PTHREADS
  239. thread->pthread_data = RT_NULL;
  240. #endif /* RT_USING_PTHREADS */
  241. #ifdef RT_USING_MODULE
  242. thread->parent.module_id = 0;
  243. #endif /* RT_USING_MODULE */
  244. rt_spin_lock_init(&thread->spinlock);
  245. RT_OBJECT_HOOKLIST_CALL(rt_thread_inited, (thread));
  246. return RT_EOK;
  247. }
  248. /**
  249. * @addtogroup group_thread_management
  250. * @{
  251. */
  252. /**
  253. * @brief This function will initialize a thread. It's used to initialize a
  254. * static thread object.
  255. *
  256. * @param thread Thread handle. Thread handle is provided by the user and
  257. * points to the corresponding thread control block memory address.
  258. *
  259. * @param name Name of the thread (shall be unique); the maximum length of the
  260. * thread name is specified by the `RT_NAME_MAX` macro defined in
  261. * `rtconfig.h`, and the extra part is automatically truncated.
  262. *
  263. * @param entry Entry function of thread.
  264. *
  265. * @param parameter Parameter of thread entry function.
  266. *
  267. * @param stack_start Start address of thread stack.
  268. *
  269. * @param stack_size Size of thread stack in bytes. Stack space address
  270. * alignment is required in most systems (for example,
  271. * alignment to 4-byte addresses in the ARM architecture).
  272. *
  273. * @param priority Priority of thread. The priority range is based on the
  274. * system configuration (macro definition `RT_THREAD_PRIORITY_MAX`
  275. * in `rtconfig.h`). If 256 levels of priority are supported,
  276. * the range is from 0 to 255. The smaller the value, the
  277. * higher the priority, and 0 is the highest priority.
  278. *
  279. * @param tick Time slice if there are same priority thread. The unit of the
  280. * time slice (tick) is the tick of the operating system. When
  281. * there are threads with the same priority in the system, this
  282. * parameter specifies the maximum length of time of a thread for
  283. * one schedule. At the end of this time slice run, the scheduler
  284. * automatically selects the next ready state of the same priority
  285. * thread to run.
  286. *
  287. * @return Return the operation status. If the return value is `RT_EOK`, the
  288. * function is successfully executed.
  289. * If the return value is any other values, it means this operation failed.
  290. */
  291. rt_err_t rt_thread_init(struct rt_thread *thread,
  292. const char *name,
  293. void (*entry)(void *parameter),
  294. void *parameter,
  295. void *stack_start,
  296. rt_uint32_t stack_size,
  297. rt_uint8_t priority,
  298. rt_uint32_t tick)
  299. {
  300. /* parameter check */
  301. RT_ASSERT(thread != RT_NULL);
  302. RT_ASSERT(stack_start != RT_NULL);
  303. RT_ASSERT(tick != 0);
  304. /* clean memory data of thread */
  305. rt_memset(thread, 0x0, sizeof(struct rt_thread));
  306. /* initialize thread object */
  307. rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name);
  308. return _thread_init(thread,
  309. name,
  310. entry,
  311. parameter,
  312. stack_start,
  313. stack_size,
  314. priority,
  315. tick);
  316. }
  317. RTM_EXPORT(rt_thread_init);
  318. /**
  319. * @brief This function will return self thread object.
  320. *
  321. * @return The self thread object. If returns `RT_NULL`, it means that the
  322. * scheduler has not started yet.
  323. */
  324. rt_thread_t rt_thread_self(void)
  325. {
  326. #ifndef RT_USING_SMP
  327. return rt_cpu_self()->current_thread;
  328. #elif defined (ARCH_USING_HW_THREAD_SELF)
  329. return rt_hw_thread_self();
  330. #else /* !ARCH_USING_HW_THREAD_SELF */
  331. rt_thread_t self;
  332. rt_base_t lock;
  333. lock = rt_hw_local_irq_disable();
  334. self = rt_cpu_self()->current_thread;
  335. rt_hw_local_irq_enable(lock);
  336. return self;
  337. #endif /* ARCH_USING_HW_THREAD_SELF */
  338. }
  339. RTM_EXPORT(rt_thread_self);
  340. /**
  341. * @brief This function will start a thread and put it to system ready queue.
  342. *
  343. * @param thread Handle of the thread to be started.
  344. *
  345. * @return Return the operation status. If the return value is `RT_EOK`, the
  346. * function is successfully executed.
  347. * If the return value is any other values, it means this operation failed.
  348. */
  349. rt_err_t rt_thread_startup(rt_thread_t thread)
  350. {
  351. /* parameter check */
  352. RT_ASSERT(thread != RT_NULL);
  353. RT_ASSERT((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT);
  354. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  355. LOG_D("startup a thread:%s with priority:%d",
  356. thread->parent.name, RT_SCHED_PRIV(thread).current_priority);
  357. /* calculate priority attribute and reset thread stat to suspend */
  358. rt_sched_thread_startup(thread);
  359. /* resume and do a schedule if scheduler is available */
  360. rt_thread_resume(thread);
  361. return RT_EOK;
  362. }
  363. RTM_EXPORT(rt_thread_startup);
  364. /**
  365. * @brief This function will close a thread. The thread object will be removed from
  366. * thread queue and detached/deleted from the system object management.
  367. * It's different from rt_thread_delete or rt_thread_detach that this will not enqueue
  368. * the closing thread to cleanup queue.
  369. *
  370. * @param thread is the thread to be closed.
  371. *
  372. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  373. * If the return value is any other values, it means this operation failed.
  374. */
  375. rt_err_t rt_thread_close(rt_thread_t thread)
  376. {
  377. rt_sched_lock_level_t slvl;
  378. rt_uint8_t thread_status;
  379. /* forbid scheduling on current core if closing current thread */
  380. RT_ASSERT(thread != rt_thread_self() || rt_critical_level());
  381. /* before checking status of scheduler */
  382. rt_sched_lock(&slvl);
  383. /* check if thread is already closed */
  384. thread_status = rt_sched_thread_get_stat(thread);
  385. if (thread_status != RT_THREAD_CLOSE)
  386. {
  387. if (thread_status != RT_THREAD_INIT)
  388. {
  389. /* remove from schedule */
  390. rt_sched_remove_thread(thread);
  391. }
  392. /* release thread timer */
  393. rt_timer_detach(&(thread->thread_timer));
  394. /* change stat */
  395. rt_sched_thread_close(thread);
  396. }
  397. /* scheduler works are done */
  398. rt_sched_unlock(slvl);
  399. return RT_EOK;
  400. }
  401. RTM_EXPORT(rt_thread_close);
  402. static rt_err_t _thread_detach(rt_thread_t thread);
  403. /**
  404. * @brief This function will detach a thread. The thread object will be removed from
  405. * thread queue and detached/deleted from the system object management.
  406. *
  407. * @param thread Handle of the thread to be deleted. The thread must be
  408. * initialized by `rt_thread_init()`.
  409. *
  410. * @return Return the operation status. If the return value is `RT_EOK`, the
  411. * function is successfully executed.
  412. * If the return value is any other values, it means this operation failed.
  413. */
  414. rt_err_t rt_thread_detach(rt_thread_t thread)
  415. {
  416. /* parameter check */
  417. RT_ASSERT(thread != RT_NULL);
  418. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  419. RT_ASSERT(rt_object_is_systemobject((rt_object_t)thread));
  420. return _thread_detach(thread);
  421. }
  422. RTM_EXPORT(rt_thread_detach);
  423. static rt_err_t _thread_detach(rt_thread_t thread)
  424. {
  425. rt_err_t error;
  426. rt_base_t critical_level;
  427. /**
  428. * forbid scheduling on current core before returning since current thread
  429. * may be detached from scheduler.
  430. */
  431. critical_level = rt_enter_critical();
  432. error = rt_thread_close(thread);
  433. _thread_detach_from_mutex(thread);
  434. /* insert to defunct thread list */
  435. rt_thread_defunct_enqueue(thread);
  436. rt_exit_critical_safe(critical_level);
  437. return error;
  438. }
  439. #ifdef RT_USING_HEAP
  440. /**
  441. * @brief This function will create a thread object and allocate thread object memory.
  442. * and stack.
  443. *
  444. * @param name The name of the thread (shall be unique.); the maximum length of
  445. * the thread name is specified by macro `RT_NAME_MAX` in `rtconfig.h`,
  446. * and the extra part is automatically truncated.
  447. *
  448. * @param entry Entry function of thread.
  449. *
  450. * @param parameter Parameter of thread entry function.
  451. *
  452. * @param stack_size Size of thread stack in bytes.
  453. *
  454. * @param priority Priority of thread. The priority range is based on the
  455. * system configuration (macro definition `RT_THREAD_PRIORITY_MAX`
  456. * in rtconfig.h). If 256-level priority is supported, then
  457. * the range is from 0 to 255. The smaller the value, the
  458. * higher the priority, and 0 is the highest priority.
  459. *
  460. * @param tick Time slice if there are same priority thread. The unit of the
  461. * time slice (tick) is the tick of the operating system. When
  462. * there are threads with the same priority in the system, this
  463. * parameter specifies the maximum length of time of a thread for
  464. * one schedule. At the end of this time slice run, the scheduler
  465. * automatically selects the next ready state of the same priority
  466. * thread to run.
  467. *
  468. * @return If the return value is a `rt_thread` structure pointer, the function is successfully executed.
  469. * If the return value is `RT_NULL`, it means this operation failed.
  470. */
  471. rt_thread_t rt_thread_create(const char *name,
  472. void (*entry)(void *parameter),
  473. void *parameter,
  474. rt_uint32_t stack_size,
  475. rt_uint8_t priority,
  476. rt_uint32_t tick)
  477. {
  478. /* parameter check */
  479. RT_ASSERT(tick != 0);
  480. struct rt_thread *thread;
  481. void *stack_start;
  482. thread = (struct rt_thread *)rt_object_allocate(RT_Object_Class_Thread,
  483. name);
  484. if (thread == RT_NULL)
  485. return RT_NULL;
  486. stack_start = (void *)RT_KERNEL_MALLOC(stack_size);
  487. if (stack_start == RT_NULL)
  488. {
  489. /* allocate stack failure */
  490. rt_object_delete((rt_object_t)thread);
  491. return RT_NULL;
  492. }
  493. _thread_init(thread,
  494. name,
  495. entry,
  496. parameter,
  497. stack_start,
  498. stack_size,
  499. priority,
  500. tick);
  501. return thread;
  502. }
  503. RTM_EXPORT(rt_thread_create);
  504. /**
  505. * @brief This function will delete a thread. The thread object will be removed from
  506. * thread queue and deleted from system object management in the idle thread.
  507. *
  508. * @param thread Handle of the thread to be deleted.
  509. *
  510. * @return Return the operation status. If the return value is `RT_EOK`, the
  511. * function is successfully executed.
  512. * If the return value is any other values, it means this operation failed.
  513. */
  514. rt_err_t rt_thread_delete(rt_thread_t thread)
  515. {
  516. /* parameter check */
  517. RT_ASSERT(thread != RT_NULL);
  518. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  519. RT_ASSERT(rt_object_is_systemobject((rt_object_t)thread) == RT_FALSE);
  520. return _thread_detach(thread);
  521. }
  522. RTM_EXPORT(rt_thread_delete);
  523. #endif /* RT_USING_HEAP */
  524. /**
  525. * @brief This function will let current thread yield processor, and scheduler will
  526. * choose the highest thread to run. After yield processor, the current thread
  527. * is still in READY state.
  528. *
  529. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  530. * If the return value is any other values, it means this operation failed.
  531. */
  532. rt_err_t rt_thread_yield(void)
  533. {
  534. rt_sched_lock_level_t slvl;
  535. rt_sched_lock(&slvl);
  536. rt_sched_thread_yield(rt_thread_self());
  537. rt_sched_unlock_n_resched(slvl);
  538. return RT_EOK;
  539. }
  540. RTM_EXPORT(rt_thread_yield);
  541. /**
  542. * @brief This function will let current thread sleep for some ticks. Change current thread state to suspend,
  543. * when the thread timer reaches the tick value, scheduler will awaken this thread.
  544. *
  545. * @param tick is the sleep ticks.
  546. *
  547. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  548. * If the return value is any other values, it means this operation failed.
  549. */
  550. static rt_err_t _thread_sleep(rt_tick_t tick)
  551. {
  552. struct rt_thread *thread;
  553. rt_base_t critical_level;
  554. int err;
  555. if (tick == 0)
  556. {
  557. return -RT_EINVAL;
  558. }
  559. /* set to current thread */
  560. thread = rt_thread_self();
  561. RT_ASSERT(thread != RT_NULL);
  562. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  563. /* current context checking */
  564. RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE);
  565. /* reset thread error */
  566. thread->error = RT_EOK;
  567. /* lock scheduler since current thread may be suspended */
  568. critical_level = rt_enter_critical();
  569. /* suspend thread */
  570. err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE);
  571. /* reset the timeout of thread timer and start it */
  572. if (err == RT_EOK)
  573. {
  574. rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick);
  575. rt_timer_start(&(thread->thread_timer));
  576. thread->error = -RT_EINTR;
  577. /* notify a pending rescheduling */
  578. rt_schedule();
  579. /* exit critical and do a rescheduling */
  580. rt_exit_critical_safe(critical_level);
  581. /* clear error number of this thread to RT_EOK */
  582. if (thread->error == -RT_ETIMEOUT)
  583. thread->error = RT_EOK;
  584. }
  585. else
  586. {
  587. rt_exit_critical_safe(critical_level);
  588. }
  589. return err;
  590. }
  591. /**
  592. * @brief This function will let current thread delay for some ticks.
  593. *
  594. * @param tick The delay ticks, in units of 1 OS Tick.
  595. *
  596. * @return Return the operation status. If the return value is `RT_EOK`, the
  597. * function is successfully executed.
  598. * If the return value is any other values, it means this operation failed.
  599. */
  600. rt_err_t rt_thread_delay(rt_tick_t tick)
  601. {
  602. return _thread_sleep(tick);
  603. }
  604. RTM_EXPORT(rt_thread_delay);
  605. /**
  606. * @brief This function will let current thread delay until (*tick + inc_tick).
  607. *
  608. * @param tick is the tick of last wakeup.
  609. *
  610. * @param inc_tick is the increment tick.
  611. *
  612. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  613. * If the return value is any other values, it means this operation failed.
  614. */
  615. rt_err_t rt_thread_delay_until(rt_tick_t *tick, rt_tick_t inc_tick)
  616. {
  617. struct rt_thread *thread;
  618. rt_tick_t cur_tick;
  619. rt_base_t critical_level;
  620. RT_ASSERT(tick != RT_NULL);
  621. /* set to current thread */
  622. thread = rt_thread_self();
  623. RT_ASSERT(thread != RT_NULL);
  624. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  625. /* reset thread error */
  626. thread->error = RT_EOK;
  627. /* disable interrupt */
  628. critical_level = rt_enter_critical();
  629. cur_tick = rt_tick_get();
  630. if (cur_tick - *tick < inc_tick)
  631. {
  632. rt_tick_t left_tick;
  633. *tick += inc_tick;
  634. left_tick = *tick - cur_tick;
  635. /* suspend thread */
  636. rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE);
  637. /* reset the timeout of thread timer and start it */
  638. rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &left_tick);
  639. rt_timer_start(&(thread->thread_timer));
  640. rt_exit_critical_safe(critical_level);
  641. rt_schedule();
  642. /* clear error number of this thread to RT_EOK */
  643. if (thread->error == -RT_ETIMEOUT)
  644. {
  645. thread->error = RT_EOK;
  646. }
  647. }
  648. else
  649. {
  650. *tick = cur_tick;
  651. rt_exit_critical_safe(critical_level);
  652. }
  653. return thread->error;
  654. }
  655. RTM_EXPORT(rt_thread_delay_until);
  656. /**
  657. * @brief This function will let current thread delay for some milliseconds.
  658. *
  659. * @param ms The delay time in units of 1ms.
  660. *
  661. * @return Return the operation status. If the return value is `RT_EOK`, the
  662. * function is successfully executed.
  663. * If the return value is any other values, it means this operation failed.
  664. */
  665. rt_err_t rt_thread_mdelay(rt_int32_t ms)
  666. {
  667. rt_tick_t tick;
  668. tick = rt_tick_from_millisecond(ms);
  669. return _thread_sleep(tick);
  670. }
  671. RTM_EXPORT(rt_thread_mdelay);
  672. #ifdef RT_USING_SMP
  673. #endif
  674. /**
  675. * @brief This function will control thread behaviors according to control command.
  676. *
  677. * @param thread Handle of the thread to be controlled.
  678. *
  679. * @param cmd Control command, which includes.
  680. * - `RT_THREAD_CTRL_CHANGE_PRIORITY` for changing priority level of thread.
  681. * - `RT_THREAD_CTRL_STARTUP` for starting a thread, equivalent to
  682. * the `rt_thread_startup()` function call.
  683. * - `RT_THREAD_CTRL_CLOSE` for closing a thread, equivalent to the
  684. * `rt_thread_delete()` function call.
  685. * - `RT_THREAD_CTRL_BIND_CPU` for bind the thread to a CPU.
  686. * - `RT_THREAD_CTRL_RESET_PRIORITY` for reset priority level of thread.
  687. *
  688. * @param arg Argument of control command.
  689. *
  690. * @return Return the operation status. If the return value is `RT_EOK`, the
  691. * function is successfully executed.
  692. * If the return value is any other values, it means this operation failed.
  693. */
  694. rt_err_t rt_thread_control(rt_thread_t thread, int cmd, void *arg)
  695. {
  696. /* parameter check */
  697. RT_ASSERT(thread != RT_NULL);
  698. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  699. switch (cmd)
  700. {
  701. case RT_THREAD_CTRL_CHANGE_PRIORITY:
  702. {
  703. rt_err_t error;
  704. rt_sched_lock_level_t slvl;
  705. rt_sched_lock(&slvl);
  706. error = rt_sched_thread_change_priority(thread, *(rt_uint8_t *)arg);
  707. rt_sched_unlock(slvl);
  708. return error;
  709. }
  710. case RT_THREAD_CTRL_RESET_PRIORITY:
  711. {
  712. rt_err_t error;
  713. rt_sched_lock_level_t slvl;
  714. rt_sched_lock(&slvl);
  715. error = rt_sched_thread_reset_priority(thread, *(rt_uint8_t *)arg);
  716. rt_sched_unlock(slvl);
  717. return error;
  718. }
  719. case RT_THREAD_CTRL_STARTUP:
  720. {
  721. return rt_thread_startup(thread);
  722. }
  723. case RT_THREAD_CTRL_CLOSE:
  724. {
  725. rt_err_t rt_err = -RT_EINVAL;
  726. if (rt_object_is_systemobject((rt_object_t)thread) == RT_TRUE)
  727. {
  728. rt_err = rt_thread_detach(thread);
  729. }
  730. #ifdef RT_USING_HEAP
  731. else
  732. {
  733. rt_err = rt_thread_delete(thread);
  734. }
  735. #endif /* RT_USING_HEAP */
  736. rt_schedule();
  737. return rt_err;
  738. }
  739. case RT_THREAD_CTRL_BIND_CPU:
  740. {
  741. rt_uint8_t cpu;
  742. cpu = (rt_uint8_t)(rt_size_t)arg;
  743. return rt_sched_thread_bind_cpu(thread, cpu);
  744. }
  745. default:
  746. break;
  747. }
  748. return RT_EOK;
  749. }
  750. RTM_EXPORT(rt_thread_control);
  751. #ifdef RT_USING_SMART
  752. #include <lwp_signal.h>
  753. #endif
  754. /* Convert suspend_flag to corresponding thread suspend state value */
  755. static rt_uint8_t _thread_get_suspend_state(int suspend_flag)
  756. {
  757. switch (suspend_flag)
  758. {
  759. case RT_INTERRUPTIBLE:
  760. return RT_THREAD_SUSPEND_INTERRUPTIBLE;
  761. case RT_KILLABLE:
  762. return RT_THREAD_SUSPEND_KILLABLE;
  763. case RT_UNINTERRUPTIBLE:
  764. default:
  765. return RT_THREAD_SUSPEND_UNINTERRUPTIBLE;
  766. }
  767. }
  768. static void _thread_set_suspend_state(struct rt_thread *thread, int suspend_flag)
  769. {
  770. rt_uint8_t stat;
  771. RT_ASSERT(thread != RT_NULL);
  772. stat = _thread_get_suspend_state(suspend_flag);
  773. RT_SCHED_CTX(thread).stat = stat | (RT_SCHED_CTX(thread).stat & ~RT_THREAD_STAT_MASK);
  774. }
  775. /**
  776. * @brief This function will suspend the specified thread and change it to suspend state.
  777. *
  778. * @note This function ONLY can suspend current thread itself.
  779. * rt_thread_suspend(rt_thread_self());
  780. *
  781. * Do not use the rt_thread_suspend to suspend other threads. You have no way of knowing what code a
  782. * thread is executing when you suspend it. If you suspend a thread while sharing a resouce with
  783. * other threads and occupying this resouce, starvation can occur very easily.
  784. *
  785. * @param thread the thread to be suspended.
  786. * @param susp_list the list thread enqueued to. RT_NULL if no list.
  787. * @param ipc_flags is a flag for the thread object to be suspended. It determines how the thread is suspended.
  788. * The flag can be ONE of the following values:
  789. * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority.
  790. * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method
  791. * (also known as first-come-first-served (FCFS) scheduling strategy).
  792. * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use
  793. * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about
  794. * the first-in-first-out principle, and you clearly understand that all threads involved in
  795. * this semaphore will become non-real-time threads.
  796. * @param suspend_flag status flag of the thread to be suspended.
  797. *
  798. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  799. * If the return value is any other values, it means this operation failed.
  800. */
  801. rt_err_t rt_thread_suspend_to_list(rt_thread_t thread, rt_list_t *susp_list, int ipc_flags, int suspend_flag)
  802. {
  803. rt_base_t stat;
  804. rt_sched_lock_level_t slvl;
  805. /* parameter check */
  806. RT_ASSERT(thread != RT_NULL);
  807. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  808. RT_ASSERT(!rt_thread_is_idle_thread(thread));
  809. LOG_D("thread suspend: %s", thread->parent.name);
  810. rt_sched_lock(&slvl);
  811. stat = rt_sched_thread_get_stat(thread);
  812. if (stat & RT_THREAD_SUSPEND_MASK)
  813. {
  814. if (RT_SCHED_CTX(thread).sched_flag_ttmr_set == 1)
  815. {
  816. /* The new suspend operation will halt the tick timer. */
  817. LOG_D("Thread [%s]'s timer has been halted.\n", thread->parent.name);
  818. rt_sched_thread_timer_stop(thread);
  819. }
  820. /* Upgrade suspend state if new state is stricter */
  821. if (stat < _thread_get_suspend_state(suspend_flag))
  822. {
  823. _thread_set_suspend_state(thread, suspend_flag);
  824. }
  825. rt_sched_unlock(slvl);
  826. /* Already suspended, just set the status to success. */
  827. return RT_EOK;
  828. }
  829. else if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING))
  830. {
  831. LOG_W("thread suspend: thread disorder, 0x%02x", RT_SCHED_CTX(thread).stat);
  832. rt_sched_unlock(slvl);
  833. return -RT_ERROR;
  834. }
  835. if (stat == RT_THREAD_RUNNING)
  836. {
  837. /* not suspend running status thread on other core */
  838. RT_ASSERT(thread == rt_thread_self());
  839. }
  840. #ifdef RT_USING_SMART
  841. if (thread->lwp)
  842. {
  843. rt_sched_unlock(slvl);
  844. /* check pending signals for thread before suspend */
  845. if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0)
  846. {
  847. /* not to suspend */
  848. return -RT_EINTR;
  849. }
  850. rt_sched_lock(&slvl);
  851. if (stat == RT_THREAD_READY)
  852. {
  853. stat = rt_sched_thread_get_stat(thread);
  854. if (stat != RT_THREAD_READY)
  855. {
  856. /* status updated while we check for signal */
  857. rt_sched_unlock(slvl);
  858. return -RT_ERROR;
  859. }
  860. }
  861. }
  862. #endif
  863. /* change thread stat */
  864. rt_sched_remove_thread(thread);
  865. _thread_set_suspend_state(thread, suspend_flag);
  866. if (susp_list)
  867. {
  868. /**
  869. * enqueue thread on the push list before leaving critical region of
  870. * scheduler, so we won't miss notification of async events.
  871. */
  872. rt_susp_list_enqueue(susp_list, thread, ipc_flags);
  873. }
  874. /* stop thread timer anyway */
  875. rt_sched_thread_timer_stop(thread);
  876. rt_sched_unlock(slvl);
  877. RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread));
  878. return RT_EOK;
  879. }
  880. RTM_EXPORT(rt_thread_suspend_to_list);
  881. /**
  882. * @brief This function will suspend the specified thread and change it to suspend state.
  883. *
  884. * @note This function ONLY can suspend current thread itself.
  885. * rt_thread_suspend(rt_thread_self());
  886. *
  887. * Do not use the rt_thread_suspend to suspend other threads. You have no way of knowing what code a
  888. * thread is executing when you suspend it. If you suspend a thread while sharing a resouce with
  889. * other threads and occupying this resouce, starvation can occur very easily.
  890. *
  891. * @param thread the thread to be suspended.
  892. * @param suspend_flag status flag of the thread to be suspended.
  893. *
  894. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  895. * If the return value is any other values, it means this operation failed.
  896. */
  897. rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag)
  898. {
  899. return rt_thread_suspend_to_list(thread, RT_NULL, 0, suspend_flag);
  900. }
  901. RTM_EXPORT(rt_thread_suspend_with_flag);
  902. /**
  903. * @brief This function will suspend the specified thread and change it to suspend state.
  904. *
  905. * @note This function can suspend both the current thread itself and other threads.
  906. * Please use this API with extreme caution when suspending other threads.
  907. *
  908. * When suspending the current thread:
  909. * rt_thread_suspend(rt_thread_self());
  910. * This is generally safe as the thread voluntarily suspends itself.
  911. *
  912. * When suspending other threads:
  913. * You have no way of knowing what code another thread is executing when you suspend it.
  914. * If you suspend a thread while it is sharing a resource with other threads and occupying
  915. * this resource (such as holding a mutex, semaphore, or other synchronization objects),
  916. * deadlock or resource starvation can occur very easily.
  917. *
  918. * @warning Suspending other threads arbitrarily can lead to:
  919. * - Deadlock situations
  920. * - Resource starvation
  921. * - System instability
  922. * - Unpredictable behavior
  923. *
  924. * Only suspend other threads when you have full control over the system state
  925. * and understand the implications.
  926. *
  927. * @param thread Handle of the thread to be suspended. Can be the current thread
  928. * (rt_thread_self()) or any other thread.
  929. *
  930. * @return Return the operation status. If the return value is `RT_EOK`, the
  931. * function is successfully executed.
  932. * If the return value is any other values, it means this operation failed.
  933. */
  934. rt_err_t rt_thread_suspend(rt_thread_t thread)
  935. {
  936. return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE);
  937. }
  938. RTM_EXPORT(rt_thread_suspend);
  939. /**
  940. * @brief This function will resume a thread and put it to system ready queue.
  941. *
  942. * @param thread Handle of the thread to be resumed.
  943. *
  944. * @return Return the operation status. If the return value is `RT_EOK`, the
  945. * function is successfully executed.
  946. * If the return value is any other values, it means this operation failed.
  947. */
  948. rt_err_t rt_thread_resume(rt_thread_t thread)
  949. {
  950. rt_sched_lock_level_t slvl;
  951. rt_err_t error;
  952. /* parameter check */
  953. RT_ASSERT(thread != RT_NULL);
  954. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  955. LOG_D("thread resume: %s", thread->parent.name);
  956. rt_sched_lock(&slvl);
  957. error = rt_sched_thread_ready(thread);
  958. if (!error)
  959. {
  960. error = rt_sched_unlock_n_resched(slvl);
  961. /**
  962. * RT_ESCHEDLOCKED indicates that the current thread is in a critical section,
  963. * rather than 'thread' can't be resumed. Therefore, we can ignore this error.
  964. */
  965. if (error == -RT_ESCHEDLOCKED)
  966. {
  967. error = RT_EOK;
  968. }
  969. }
  970. else
  971. {
  972. rt_sched_unlock(slvl);
  973. }
  974. RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread));
  975. return error;
  976. }
  977. RTM_EXPORT(rt_thread_resume);
  978. #ifdef RT_USING_SMART
  979. /**
  980. * This function will wakeup a thread with customized operation.
  981. *
  982. * @param thread the thread to be resumed
  983. *
  984. * @return the operation status, RT_EOK on OK, -RT_ERROR on error
  985. */
  986. rt_err_t rt_thread_wakeup(rt_thread_t thread)
  987. {
  988. rt_sched_lock_level_t slvl;
  989. rt_err_t ret;
  990. rt_wakeup_func_t func = RT_NULL;
  991. RT_ASSERT(thread != RT_NULL);
  992. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  993. rt_sched_lock(&slvl);
  994. func = thread->wakeup_handle.func;
  995. thread->wakeup_handle.func = RT_NULL;
  996. rt_sched_unlock(slvl);
  997. if (func)
  998. {
  999. ret = func(thread->wakeup_handle.user_data, thread);
  1000. }
  1001. else
  1002. {
  1003. ret = rt_thread_resume(thread);
  1004. }
  1005. return ret;
  1006. }
  1007. RTM_EXPORT(rt_thread_wakeup);
  1008. void rt_thread_wakeup_set(struct rt_thread *thread, rt_wakeup_func_t func, void* user_data)
  1009. {
  1010. rt_sched_lock_level_t slvl;
  1011. RT_ASSERT(thread != RT_NULL);
  1012. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  1013. rt_sched_lock(&slvl);
  1014. thread->wakeup_handle.func = func;
  1015. thread->wakeup_handle.user_data = user_data;
  1016. rt_sched_unlock(slvl);
  1017. }
  1018. RTM_EXPORT(rt_thread_wakeup_set);
  1019. #endif
  1020. /**
  1021. * @brief This function will find the specified thread.
  1022. *
  1023. * @note Please don't invoke this function in interrupt status.
  1024. *
  1025. * @param name is the name of thread finding.
  1026. *
  1027. * @return If the return value is a rt_thread structure pointer, the function is successfully executed.
  1028. * If the return value is RT_NULL, it means this operation failed.
  1029. */
  1030. rt_thread_t rt_thread_find(char *name)
  1031. {
  1032. return (rt_thread_t)rt_object_find(name, RT_Object_Class_Thread);
  1033. }
  1034. RTM_EXPORT(rt_thread_find);
  1035. /**
  1036. * @brief This function will return the name of the specified thread
  1037. *
  1038. * @note Please don't invoke this function in interrupt status
  1039. *
  1040. * @param thread the thread to retrieve thread name
  1041. * @param name buffer to store the thread name string
  1042. * @param name_size maximum size of the buffer to store the thread name
  1043. *
  1044. * @return If the return value is RT_EOK, the function is successfully executed
  1045. * If the return value is -RT_EINVAL, it means this operation failed
  1046. */
  1047. rt_err_t rt_thread_get_name(rt_thread_t thread, char *name, rt_uint8_t name_size)
  1048. {
  1049. return (thread == RT_NULL) ? -RT_EINVAL : rt_object_get_name(&thread->parent, name, name_size);
  1050. }
  1051. RTM_EXPORT(rt_thread_get_name);
  1052. /** @} group_thread_management */