thread.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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_PTHREADS
  233. thread->pthread_data = RT_NULL;
  234. #endif /* RT_USING_PTHREADS */
  235. #ifdef RT_USING_MODULE
  236. thread->parent.module_id = 0;
  237. #endif /* RT_USING_MODULE */
  238. rt_spin_lock_init(&thread->spinlock);
  239. RT_OBJECT_HOOKLIST_CALL(rt_thread_inited, (thread));
  240. return RT_EOK;
  241. }
  242. /**
  243. * @addtogroup group_thread_management
  244. * @{
  245. */
  246. /**
  247. * @brief This function will initialize a thread. It's used to initialize a
  248. * static thread object.
  249. *
  250. * @param thread Thread handle. Thread handle is provided by the user and
  251. * points to the corresponding thread control block memory address.
  252. *
  253. * @param name Name of the thread (shall be unique); the maximum length of the
  254. * thread name is specified by the `RT_NAME_MAX` macro defined in
  255. * `rtconfig.h`, and the extra part is automatically truncated.
  256. *
  257. * @param entry Entry function of thread.
  258. *
  259. * @param parameter Parameter of thread entry function.
  260. *
  261. * @param stack_start Start address of thread stack.
  262. *
  263. * @param stack_size Size of thread stack in bytes. Stack space address
  264. * alignment is required in most systems (for example,
  265. * alignment to 4-byte addresses in the ARM architecture).
  266. *
  267. * @param priority Priority of thread. The priority range is based on the
  268. * system configuration (macro definition `RT_THREAD_PRIORITY_MAX`
  269. * in `rtconfig.h`). If 256 levels of priority are supported,
  270. * the range is from 0 to 255. The smaller the value, the
  271. * higher the priority, and 0 is the highest priority.
  272. *
  273. * @param tick Time slice if there are same priority thread. The unit of the
  274. * time slice (tick) is the tick of the operating system. When
  275. * there are threads with the same priority in the system, this
  276. * parameter specifies the maximum length of time of a thread for
  277. * one schedule. At the end of this time slice run, the scheduler
  278. * automatically selects the next ready state of the same priority
  279. * thread to run.
  280. *
  281. * @return Return the operation status. If the return value is `RT_EOK`, the
  282. * function is successfully executed.
  283. * If the return value is any other values, it means this operation failed.
  284. */
  285. rt_err_t rt_thread_init(struct rt_thread *thread,
  286. const char *name,
  287. void (*entry)(void *parameter),
  288. void *parameter,
  289. void *stack_start,
  290. rt_uint32_t stack_size,
  291. rt_uint8_t priority,
  292. rt_uint32_t tick)
  293. {
  294. /* parameter check */
  295. RT_ASSERT(thread != RT_NULL);
  296. RT_ASSERT(stack_start != RT_NULL);
  297. RT_ASSERT(tick != 0);
  298. /* clean memory data of thread */
  299. rt_memset(thread, 0x0, sizeof(struct rt_thread));
  300. /* initialize thread object */
  301. rt_object_init((rt_object_t)thread, RT_Object_Class_Thread, name);
  302. return _thread_init(thread,
  303. name,
  304. entry,
  305. parameter,
  306. stack_start,
  307. stack_size,
  308. priority,
  309. tick);
  310. }
  311. RTM_EXPORT(rt_thread_init);
  312. /**
  313. * @brief This function will return self thread object.
  314. *
  315. * @return The self thread object. If returns `RT_NULL`, it means that the
  316. * scheduler has not started yet.
  317. */
  318. rt_thread_t rt_thread_self(void)
  319. {
  320. #ifndef RT_USING_SMP
  321. return rt_cpu_self()->current_thread;
  322. #elif defined (ARCH_USING_HW_THREAD_SELF)
  323. return rt_hw_thread_self();
  324. #else /* !ARCH_USING_HW_THREAD_SELF */
  325. rt_thread_t self;
  326. rt_base_t lock;
  327. lock = rt_hw_local_irq_disable();
  328. self = rt_cpu_self()->current_thread;
  329. rt_hw_local_irq_enable(lock);
  330. return self;
  331. #endif /* ARCH_USING_HW_THREAD_SELF */
  332. }
  333. RTM_EXPORT(rt_thread_self);
  334. /**
  335. * @brief This function will start a thread and put it to system ready queue.
  336. *
  337. * @param thread Handle of the thread to be started.
  338. *
  339. * @return Return the operation status. If the return value is `RT_EOK`, the
  340. * function is successfully executed.
  341. * If the return value is any other values, it means this operation failed.
  342. */
  343. rt_err_t rt_thread_startup(rt_thread_t thread)
  344. {
  345. /* parameter check */
  346. RT_ASSERT(thread != RT_NULL);
  347. RT_ASSERT((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_MASK) == RT_THREAD_INIT);
  348. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  349. LOG_D("startup a thread:%s with priority:%d",
  350. thread->parent.name, RT_SCHED_PRIV(thread).current_priority);
  351. /* calculate priority attribute and reset thread stat to suspend */
  352. rt_sched_thread_startup(thread);
  353. /* resume and do a schedule if scheduler is available */
  354. rt_thread_resume(thread);
  355. return RT_EOK;
  356. }
  357. RTM_EXPORT(rt_thread_startup);
  358. /**
  359. * @brief This function will close a thread. The thread object will be removed from
  360. * thread queue and detached/deleted from the system object management.
  361. * It's different from rt_thread_delete or rt_thread_detach that this will not enqueue
  362. * the closing thread to cleanup queue.
  363. *
  364. * @param thread is the thread to be closed.
  365. *
  366. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  367. * If the return value is any other values, it means this operation failed.
  368. */
  369. rt_err_t rt_thread_close(rt_thread_t thread)
  370. {
  371. rt_sched_lock_level_t slvl;
  372. rt_uint8_t thread_status;
  373. /* forbid scheduling on current core if closing current thread */
  374. RT_ASSERT(thread != rt_thread_self() || rt_critical_level());
  375. /* before checking status of scheduler */
  376. rt_sched_lock(&slvl);
  377. /* check if thread is already closed */
  378. thread_status = rt_sched_thread_get_stat(thread);
  379. if (thread_status != RT_THREAD_CLOSE)
  380. {
  381. if (thread_status != RT_THREAD_INIT)
  382. {
  383. /* remove from schedule */
  384. rt_sched_remove_thread(thread);
  385. }
  386. /* release thread timer */
  387. rt_timer_detach(&(thread->thread_timer));
  388. /* change stat */
  389. rt_sched_thread_close(thread);
  390. }
  391. /* scheduler works are done */
  392. rt_sched_unlock(slvl);
  393. return RT_EOK;
  394. }
  395. RTM_EXPORT(rt_thread_close);
  396. static rt_err_t _thread_detach(rt_thread_t thread);
  397. /**
  398. * @brief This function will detach a thread. The thread object will be removed from
  399. * thread queue and detached/deleted from the system object management.
  400. *
  401. * @param thread Handle of the thread to be deleted. The thread must be
  402. * initialized by `rt_thread_init()`.
  403. *
  404. * @return Return the operation status. If the return value is `RT_EOK`, the
  405. * function is successfully executed.
  406. * If the return value is any other values, it means this operation failed.
  407. */
  408. rt_err_t rt_thread_detach(rt_thread_t thread)
  409. {
  410. /* parameter check */
  411. RT_ASSERT(thread != RT_NULL);
  412. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  413. RT_ASSERT(rt_object_is_systemobject((rt_object_t)thread));
  414. return _thread_detach(thread);
  415. }
  416. RTM_EXPORT(rt_thread_detach);
  417. static rt_err_t _thread_detach(rt_thread_t thread)
  418. {
  419. rt_err_t error;
  420. rt_base_t critical_level;
  421. /**
  422. * forbid scheduling on current core before returning since current thread
  423. * may be detached from scheduler.
  424. */
  425. critical_level = rt_enter_critical();
  426. error = rt_thread_close(thread);
  427. _thread_detach_from_mutex(thread);
  428. /* insert to defunct thread list */
  429. rt_thread_defunct_enqueue(thread);
  430. rt_exit_critical_safe(critical_level);
  431. return error;
  432. }
  433. #ifdef RT_USING_HEAP
  434. /**
  435. * @brief This function will create a thread object and allocate thread object memory.
  436. * and stack.
  437. *
  438. * @param name The name of the thread (shall be unique.); the maximum length of
  439. * the thread name is specified by macro `RT_NAME_MAX` in `rtconfig.h`,
  440. * and the extra part is automatically truncated.
  441. *
  442. * @param entry Entry function of thread.
  443. *
  444. * @param parameter Parameter of thread entry function.
  445. *
  446. * @param stack_size Size of thread stack in bytes.
  447. *
  448. * @param priority Priority of thread. The priority range is based on the
  449. * system configuration (macro definition `RT_THREAD_PRIORITY_MAX`
  450. * in rtconfig.h). If 256-level priority is supported, then
  451. * the range is from 0 to 255. The smaller the value, the
  452. * higher the priority, and 0 is the highest priority.
  453. *
  454. * @param tick Time slice if there are same priority thread. The unit of the
  455. * time slice (tick) is the tick of the operating system. When
  456. * there are threads with the same priority in the system, this
  457. * parameter specifies the maximum length of time of a thread for
  458. * one schedule. At the end of this time slice run, the scheduler
  459. * automatically selects the next ready state of the same priority
  460. * thread to run.
  461. *
  462. * @return If the return value is a `rt_thread` structure pointer, the function is successfully executed.
  463. * If the return value is `RT_NULL`, it means this operation failed.
  464. */
  465. rt_thread_t rt_thread_create(const char *name,
  466. void (*entry)(void *parameter),
  467. void *parameter,
  468. rt_uint32_t stack_size,
  469. rt_uint8_t priority,
  470. rt_uint32_t tick)
  471. {
  472. /* parameter check */
  473. RT_ASSERT(tick != 0);
  474. struct rt_thread *thread;
  475. void *stack_start;
  476. thread = (struct rt_thread *)rt_object_allocate(RT_Object_Class_Thread,
  477. name);
  478. if (thread == RT_NULL)
  479. return RT_NULL;
  480. stack_start = (void *)RT_KERNEL_MALLOC(stack_size);
  481. if (stack_start == RT_NULL)
  482. {
  483. /* allocate stack failure */
  484. rt_object_delete((rt_object_t)thread);
  485. return RT_NULL;
  486. }
  487. _thread_init(thread,
  488. name,
  489. entry,
  490. parameter,
  491. stack_start,
  492. stack_size,
  493. priority,
  494. tick);
  495. return thread;
  496. }
  497. RTM_EXPORT(rt_thread_create);
  498. /**
  499. * @brief This function will delete a thread. The thread object will be removed from
  500. * thread queue and deleted from system object management in the idle thread.
  501. *
  502. * @param thread Handle of the thread to be deleted.
  503. *
  504. * @return Return the operation status. If the return value is `RT_EOK`, the
  505. * function is successfully executed.
  506. * If the return value is any other values, it means this operation failed.
  507. */
  508. rt_err_t rt_thread_delete(rt_thread_t thread)
  509. {
  510. /* parameter check */
  511. RT_ASSERT(thread != RT_NULL);
  512. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  513. RT_ASSERT(rt_object_is_systemobject((rt_object_t)thread) == RT_FALSE);
  514. return _thread_detach(thread);
  515. }
  516. RTM_EXPORT(rt_thread_delete);
  517. #endif /* RT_USING_HEAP */
  518. /**
  519. * @brief This function will let current thread yield processor, and scheduler will
  520. * choose the highest thread to run. After yield processor, the current thread
  521. * is still in READY state.
  522. *
  523. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  524. * If the return value is any other values, it means this operation failed.
  525. */
  526. rt_err_t rt_thread_yield(void)
  527. {
  528. rt_sched_lock_level_t slvl;
  529. rt_sched_lock(&slvl);
  530. rt_sched_thread_yield(rt_thread_self());
  531. rt_sched_unlock_n_resched(slvl);
  532. return RT_EOK;
  533. }
  534. RTM_EXPORT(rt_thread_yield);
  535. /**
  536. * @brief This function will let current thread sleep for some ticks. Change current thread state to suspend,
  537. * when the thread timer reaches the tick value, scheduler will awaken this thread.
  538. *
  539. * @param tick is the sleep ticks.
  540. *
  541. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  542. * If the return value is any other values, it means this operation failed.
  543. */
  544. static rt_err_t _thread_sleep(rt_tick_t tick)
  545. {
  546. struct rt_thread *thread;
  547. rt_base_t critical_level;
  548. int err;
  549. if (tick == 0)
  550. {
  551. return -RT_EINVAL;
  552. }
  553. /* set to current thread */
  554. thread = rt_thread_self();
  555. RT_ASSERT(thread != RT_NULL);
  556. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  557. /* current context checking */
  558. RT_DEBUG_SCHEDULER_AVAILABLE(RT_TRUE);
  559. /* reset thread error */
  560. thread->error = RT_EOK;
  561. /* lock scheduler since current thread may be suspended */
  562. critical_level = rt_enter_critical();
  563. /* suspend thread */
  564. err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE);
  565. /* reset the timeout of thread timer and start it */
  566. if (err == RT_EOK)
  567. {
  568. rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick);
  569. rt_timer_start(&(thread->thread_timer));
  570. thread->error = -RT_EINTR;
  571. /* notify a pending rescheduling */
  572. rt_schedule();
  573. /* exit critical and do a rescheduling */
  574. rt_exit_critical_safe(critical_level);
  575. /* clear error number of this thread to RT_EOK */
  576. if (thread->error == -RT_ETIMEOUT)
  577. thread->error = RT_EOK;
  578. }
  579. else
  580. {
  581. rt_exit_critical_safe(critical_level);
  582. }
  583. return err;
  584. }
  585. /**
  586. * @brief This function will let current thread delay for some ticks.
  587. *
  588. * @param tick The delay ticks, in units of 1 OS Tick.
  589. *
  590. * @return Return the operation status. If the return value is `RT_EOK`, the
  591. * function is successfully executed.
  592. * If the return value is any other values, it means this operation failed.
  593. */
  594. rt_err_t rt_thread_delay(rt_tick_t tick)
  595. {
  596. return _thread_sleep(tick);
  597. }
  598. RTM_EXPORT(rt_thread_delay);
  599. /**
  600. * @brief This function will let current thread delay until (*tick + inc_tick).
  601. *
  602. * @param tick is the tick of last wakeup.
  603. *
  604. * @param inc_tick is the increment tick.
  605. *
  606. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  607. * If the return value is any other values, it means this operation failed.
  608. */
  609. rt_err_t rt_thread_delay_until(rt_tick_t *tick, rt_tick_t inc_tick)
  610. {
  611. struct rt_thread *thread;
  612. rt_tick_t cur_tick;
  613. rt_base_t critical_level;
  614. RT_ASSERT(tick != RT_NULL);
  615. /* set to current thread */
  616. thread = rt_thread_self();
  617. RT_ASSERT(thread != RT_NULL);
  618. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  619. /* reset thread error */
  620. thread->error = RT_EOK;
  621. /* disable interrupt */
  622. critical_level = rt_enter_critical();
  623. cur_tick = rt_tick_get();
  624. if (cur_tick - *tick < inc_tick)
  625. {
  626. rt_tick_t left_tick;
  627. *tick += inc_tick;
  628. left_tick = *tick - cur_tick;
  629. /* suspend thread */
  630. rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE);
  631. /* reset the timeout of thread timer and start it */
  632. rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &left_tick);
  633. rt_timer_start(&(thread->thread_timer));
  634. rt_exit_critical_safe(critical_level);
  635. rt_schedule();
  636. /* clear error number of this thread to RT_EOK */
  637. if (thread->error == -RT_ETIMEOUT)
  638. {
  639. thread->error = RT_EOK;
  640. }
  641. }
  642. else
  643. {
  644. *tick = cur_tick;
  645. rt_exit_critical_safe(critical_level);
  646. }
  647. return thread->error;
  648. }
  649. RTM_EXPORT(rt_thread_delay_until);
  650. /**
  651. * @brief This function will let current thread delay for some milliseconds.
  652. *
  653. * @param ms The delay time in units of 1ms.
  654. *
  655. * @return Return the operation status. If the return value is `RT_EOK`, the
  656. * function is successfully executed.
  657. * If the return value is any other values, it means this operation failed.
  658. */
  659. rt_err_t rt_thread_mdelay(rt_int32_t ms)
  660. {
  661. rt_tick_t tick;
  662. tick = rt_tick_from_millisecond(ms);
  663. return _thread_sleep(tick);
  664. }
  665. RTM_EXPORT(rt_thread_mdelay);
  666. #ifdef RT_USING_SMP
  667. #endif
  668. /**
  669. * @brief This function will control thread behaviors according to control command.
  670. *
  671. * @param thread Handle of the thread to be controlled.
  672. *
  673. * @param cmd Control command, which includes.
  674. * - `RT_THREAD_CTRL_CHANGE_PRIORITY` for changing priority level of thread.
  675. * - `RT_THREAD_CTRL_STARTUP` for starting a thread, equivalent to
  676. * the `rt_thread_startup()` function call.
  677. * - `RT_THREAD_CTRL_CLOSE` for closing a thread, equivalent to the
  678. * `rt_thread_delete()` function call.
  679. * - `RT_THREAD_CTRL_BIND_CPU` for bind the thread to a CPU.
  680. * - `RT_THREAD_CTRL_RESET_PRIORITY` for reset priority level of thread.
  681. *
  682. * @param arg Argument of control command.
  683. *
  684. * @return Return the operation status. If the return value is `RT_EOK`, the
  685. * function is successfully executed.
  686. * If the return value is any other values, it means this operation failed.
  687. */
  688. rt_err_t rt_thread_control(rt_thread_t thread, int cmd, void *arg)
  689. {
  690. /* parameter check */
  691. RT_ASSERT(thread != RT_NULL);
  692. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  693. switch (cmd)
  694. {
  695. case RT_THREAD_CTRL_CHANGE_PRIORITY:
  696. {
  697. rt_err_t error;
  698. rt_sched_lock_level_t slvl;
  699. rt_sched_lock(&slvl);
  700. error = rt_sched_thread_change_priority(thread, *(rt_uint8_t *)arg);
  701. rt_sched_unlock(slvl);
  702. return error;
  703. }
  704. case RT_THREAD_CTRL_RESET_PRIORITY:
  705. {
  706. rt_err_t error;
  707. rt_sched_lock_level_t slvl;
  708. rt_sched_lock(&slvl);
  709. error = rt_sched_thread_reset_priority(thread, *(rt_uint8_t *)arg);
  710. rt_sched_unlock(slvl);
  711. return error;
  712. }
  713. case RT_THREAD_CTRL_STARTUP:
  714. {
  715. return rt_thread_startup(thread);
  716. }
  717. case RT_THREAD_CTRL_CLOSE:
  718. {
  719. rt_err_t rt_err = -RT_EINVAL;
  720. if (rt_object_is_systemobject((rt_object_t)thread) == RT_TRUE)
  721. {
  722. rt_err = rt_thread_detach(thread);
  723. }
  724. #ifdef RT_USING_HEAP
  725. else
  726. {
  727. rt_err = rt_thread_delete(thread);
  728. }
  729. #endif /* RT_USING_HEAP */
  730. rt_schedule();
  731. return rt_err;
  732. }
  733. case RT_THREAD_CTRL_BIND_CPU:
  734. {
  735. rt_uint8_t cpu;
  736. cpu = (rt_uint8_t)(rt_size_t)arg;
  737. return rt_sched_thread_bind_cpu(thread, cpu);
  738. }
  739. default:
  740. break;
  741. }
  742. return RT_EOK;
  743. }
  744. RTM_EXPORT(rt_thread_control);
  745. #ifdef RT_USING_SMART
  746. #include <lwp_signal.h>
  747. #endif
  748. static void _thread_set_suspend_state(struct rt_thread *thread, int suspend_flag)
  749. {
  750. rt_uint8_t stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE;
  751. RT_ASSERT(thread != RT_NULL);
  752. switch (suspend_flag)
  753. {
  754. case RT_INTERRUPTIBLE:
  755. stat = RT_THREAD_SUSPEND_INTERRUPTIBLE;
  756. break;
  757. case RT_KILLABLE:
  758. stat = RT_THREAD_SUSPEND_KILLABLE;
  759. break;
  760. case RT_UNINTERRUPTIBLE:
  761. stat = RT_THREAD_SUSPEND_UNINTERRUPTIBLE;
  762. break;
  763. default:
  764. RT_ASSERT(0);
  765. break;
  766. }
  767. RT_SCHED_CTX(thread).stat = stat | (RT_SCHED_CTX(thread).stat & ~RT_THREAD_STAT_MASK);
  768. }
  769. /**
  770. * @brief This function will suspend the specified thread and change it to suspend state.
  771. *
  772. * @note This function ONLY can suspend current thread itself.
  773. * rt_thread_suspend(rt_thread_self());
  774. *
  775. * Do not use the rt_thread_suspend to suspend other threads. You have no way of knowing what code a
  776. * thread is executing when you suspend it. If you suspend a thread while sharing a resouce with
  777. * other threads and occupying this resouce, starvation can occur very easily.
  778. *
  779. * @param thread the thread to be suspended.
  780. * @param susp_list the list thread enqueued to. RT_NULL if no list.
  781. * @param ipc_flags is a flag for the thread object to be suspended. It determines how the thread is suspended.
  782. * The flag can be ONE of the following values:
  783. * RT_IPC_FLAG_PRIO The pending threads will queue in order of priority.
  784. * RT_IPC_FLAG_FIFO The pending threads will queue in the first-in-first-out method
  785. * (also known as first-come-first-served (FCFS) scheduling strategy).
  786. * NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to use
  787. * RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about
  788. * the first-in-first-out principle, and you clearly understand that all threads involved in
  789. * this semaphore will become non-real-time threads.
  790. * @param suspend_flag status flag of the thread to be suspended.
  791. *
  792. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  793. * If the return value is any other values, it means this operation failed.
  794. */
  795. rt_err_t rt_thread_suspend_to_list(rt_thread_t thread, rt_list_t *susp_list, int ipc_flags, int suspend_flag)
  796. {
  797. rt_base_t stat;
  798. rt_sched_lock_level_t slvl;
  799. /* parameter check */
  800. RT_ASSERT(thread != RT_NULL);
  801. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  802. LOG_D("thread suspend: %s", thread->parent.name);
  803. rt_sched_lock(&slvl);
  804. stat = rt_sched_thread_get_stat(thread);
  805. if (stat == RT_THREAD_SUSPEND)
  806. {
  807. rt_sched_unlock(slvl);
  808. /* Already suspended, just set status to success. */
  809. return RT_EOK;
  810. }
  811. else if ((stat != RT_THREAD_READY) && (stat != RT_THREAD_RUNNING))
  812. {
  813. LOG_D("thread suspend: thread disorder, 0x%2x", RT_SCHED_CTX(thread).stat);
  814. rt_sched_unlock(slvl);
  815. return -RT_ERROR;
  816. }
  817. if (stat == RT_THREAD_RUNNING)
  818. {
  819. /* not suspend running status thread on other core */
  820. RT_ASSERT(thread == rt_thread_self());
  821. }
  822. #ifdef RT_USING_SMART
  823. if (thread->lwp)
  824. {
  825. rt_sched_unlock(slvl);
  826. /* check pending signals for thread before suspend */
  827. if (lwp_thread_signal_suspend_check(thread, suspend_flag) == 0)
  828. {
  829. /* not to suspend */
  830. return -RT_EINTR;
  831. }
  832. rt_sched_lock(&slvl);
  833. if (stat == RT_THREAD_READY)
  834. {
  835. stat = rt_sched_thread_get_stat(thread);
  836. if (stat != RT_THREAD_READY)
  837. {
  838. /* status updated while we check for signal */
  839. rt_sched_unlock(slvl);
  840. return -RT_ERROR;
  841. }
  842. }
  843. }
  844. #endif
  845. /* change thread stat */
  846. rt_sched_remove_thread(thread);
  847. _thread_set_suspend_state(thread, suspend_flag);
  848. if (susp_list)
  849. {
  850. /**
  851. * enqueue thread on the push list before leaving critical region of
  852. * scheduler, so we won't miss notification of async events.
  853. */
  854. rt_susp_list_enqueue(susp_list, thread, ipc_flags);
  855. }
  856. /* stop thread timer anyway */
  857. rt_sched_thread_timer_stop(thread);
  858. rt_sched_unlock(slvl);
  859. RT_OBJECT_HOOK_CALL(rt_thread_suspend_hook, (thread));
  860. return RT_EOK;
  861. }
  862. RTM_EXPORT(rt_thread_suspend_to_list);
  863. /**
  864. * @brief This function will suspend the specified thread and change it to suspend state.
  865. *
  866. * @note This function ONLY can suspend current thread itself.
  867. * rt_thread_suspend(rt_thread_self());
  868. *
  869. * Do not use the rt_thread_suspend to suspend other threads. You have no way of knowing what code a
  870. * thread is executing when you suspend it. If you suspend a thread while sharing a resouce with
  871. * other threads and occupying this resouce, starvation can occur very easily.
  872. *
  873. * @param thread the thread to be suspended.
  874. * @param suspend_flag status flag of the thread to be suspended.
  875. *
  876. * @return Return the operation status. If the return value is RT_EOK, the function is successfully executed.
  877. * If the return value is any other values, it means this operation failed.
  878. */
  879. rt_err_t rt_thread_suspend_with_flag(rt_thread_t thread, int suspend_flag)
  880. {
  881. return rt_thread_suspend_to_list(thread, RT_NULL, 0, suspend_flag);
  882. }
  883. RTM_EXPORT(rt_thread_suspend_with_flag);
  884. /**
  885. * @brief This function will suspend the specified thread and change it to suspend state.
  886. *
  887. * @note This function can suspend both the current thread itself and other threads.
  888. * Please use this API with extreme caution when suspending other threads.
  889. *
  890. * When suspending the current thread:
  891. * rt_thread_suspend(rt_thread_self());
  892. * This is generally safe as the thread voluntarily suspends itself.
  893. *
  894. * When suspending other threads:
  895. * You have no way of knowing what code another thread is executing when you suspend it.
  896. * If you suspend a thread while it is sharing a resource with other threads and occupying
  897. * this resource (such as holding a mutex, semaphore, or other synchronization objects),
  898. * deadlock or resource starvation can occur very easily.
  899. *
  900. * @warning Suspending other threads arbitrarily can lead to:
  901. * - Deadlock situations
  902. * - Resource starvation
  903. * - System instability
  904. * - Unpredictable behavior
  905. *
  906. * Only suspend other threads when you have full control over the system state
  907. * and understand the implications.
  908. *
  909. * @param thread Handle of the thread to be suspended. Can be the current thread
  910. * (rt_thread_self()) or any other thread.
  911. *
  912. * @return Return the operation status. If the return value is `RT_EOK`, the
  913. * function is successfully executed.
  914. * If the return value is any other values, it means this operation failed.
  915. */
  916. rt_err_t rt_thread_suspend(rt_thread_t thread)
  917. {
  918. return rt_thread_suspend_with_flag(thread, RT_UNINTERRUPTIBLE);
  919. }
  920. RTM_EXPORT(rt_thread_suspend);
  921. /**
  922. * @brief This function will resume a thread and put it to system ready queue.
  923. *
  924. * @param thread Handle of the thread to be resumed.
  925. *
  926. * @return Return the operation status. If the return value is `RT_EOK`, the
  927. * function is successfully executed.
  928. * If the return value is any other values, it means this operation failed.
  929. */
  930. rt_err_t rt_thread_resume(rt_thread_t thread)
  931. {
  932. rt_sched_lock_level_t slvl;
  933. rt_err_t error;
  934. /* parameter check */
  935. RT_ASSERT(thread != RT_NULL);
  936. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  937. LOG_D("thread resume: %s", thread->parent.name);
  938. rt_sched_lock(&slvl);
  939. error = rt_sched_thread_ready(thread);
  940. if (!error)
  941. {
  942. error = rt_sched_unlock_n_resched(slvl);
  943. /**
  944. * RT_ESCHEDLOCKED indicates that the current thread is in a critical section,
  945. * rather than 'thread' can't be resumed. Therefore, we can ignore this error.
  946. */
  947. if (error == -RT_ESCHEDLOCKED)
  948. {
  949. error = RT_EOK;
  950. }
  951. }
  952. else
  953. {
  954. rt_sched_unlock(slvl);
  955. }
  956. RT_OBJECT_HOOK_CALL(rt_thread_resume_hook, (thread));
  957. return error;
  958. }
  959. RTM_EXPORT(rt_thread_resume);
  960. #ifdef RT_USING_SMART
  961. /**
  962. * This function will wakeup a thread with customized operation.
  963. *
  964. * @param thread the thread to be resumed
  965. *
  966. * @return the operation status, RT_EOK on OK, -RT_ERROR on error
  967. */
  968. rt_err_t rt_thread_wakeup(rt_thread_t thread)
  969. {
  970. rt_sched_lock_level_t slvl;
  971. rt_err_t ret;
  972. rt_wakeup_func_t func = RT_NULL;
  973. RT_ASSERT(thread != RT_NULL);
  974. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  975. rt_sched_lock(&slvl);
  976. func = thread->wakeup_handle.func;
  977. thread->wakeup_handle.func = RT_NULL;
  978. rt_sched_unlock(slvl);
  979. if (func)
  980. {
  981. ret = func(thread->wakeup_handle.user_data, thread);
  982. }
  983. else
  984. {
  985. ret = rt_thread_resume(thread);
  986. }
  987. return ret;
  988. }
  989. RTM_EXPORT(rt_thread_wakeup);
  990. void rt_thread_wakeup_set(struct rt_thread *thread, rt_wakeup_func_t func, void* user_data)
  991. {
  992. rt_sched_lock_level_t slvl;
  993. RT_ASSERT(thread != RT_NULL);
  994. RT_ASSERT(rt_object_get_type((rt_object_t)thread) == RT_Object_Class_Thread);
  995. rt_sched_lock(&slvl);
  996. thread->wakeup_handle.func = func;
  997. thread->wakeup_handle.user_data = user_data;
  998. rt_sched_unlock(slvl);
  999. }
  1000. RTM_EXPORT(rt_thread_wakeup_set);
  1001. #endif
  1002. /**
  1003. * @brief This function will find the specified thread.
  1004. *
  1005. * @note Please don't invoke this function in interrupt status.
  1006. *
  1007. * @param name is the name of thread finding.
  1008. *
  1009. * @return If the return value is a rt_thread structure pointer, the function is successfully executed.
  1010. * If the return value is RT_NULL, it means this operation failed.
  1011. */
  1012. rt_thread_t rt_thread_find(char *name)
  1013. {
  1014. return (rt_thread_t)rt_object_find(name, RT_Object_Class_Thread);
  1015. }
  1016. RTM_EXPORT(rt_thread_find);
  1017. /**
  1018. * @brief This function will return the name of the specified thread
  1019. *
  1020. * @note Please don't invoke this function in interrupt status
  1021. *
  1022. * @param thread the thread to retrieve thread name
  1023. * @param name buffer to store the thread name string
  1024. * @param name_size maximum size of the buffer to store the thread name
  1025. *
  1026. * @return If the return value is RT_EOK, the function is successfully executed
  1027. * If the return value is -RT_EINVAL, it means this operation failed
  1028. */
  1029. rt_err_t rt_thread_get_name(rt_thread_t thread, char *name, rt_uint8_t name_size)
  1030. {
  1031. return (thread == RT_NULL) ? -RT_EINVAL : rt_object_get_name(&thread->parent, name, name_size);
  1032. }
  1033. RTM_EXPORT(rt_thread_get_name);
  1034. /** @} group_thread_management */