pthread.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. /*
  2. * Copyright (c) 2006-2024 RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-01-26 Bernard Fix pthread_detach issue for a none-joinable
  9. * thread.
  10. * 2019-02-07 Bernard Add _pthread_destroy to release pthread resource.
  11. * 2022-05-10 xiangxistu Modify the recycle logic about resource of pthread.
  12. * 2024-04-15 atwww Modify the recycle logic of TLS in function _pthread_data_destroy,
  13. * make it safe for C++11's thread_local destructors.
  14. */
  15. #include <rthw.h>
  16. #include <pthread.h>
  17. #include <sched.h>
  18. #include <sys/time.h>
  19. #include "pthread_internal.h"
  20. RT_DEFINE_HW_SPINLOCK(pth_lock);
  21. _pthread_data_t *pth_table[PTHREAD_NUM_MAX] = {NULL};
  22. static int concurrency_level;
  23. /**
  24. * @brief Retrieves the private data structure of a specified thread
  25. *
  26. * This function locates and validates the thread-private data structure associated with the given thread ID.
  27. * It uses a spinlock to synchronize access to the global thread table, ensuring data consistency in multithreaded environments.
  28. * A magic number validation is performed before returning to guarantee structural integrity.
  29. *
  30. * @param thread Thread ID used to index into the global thread data table
  31. *
  32. * @return Pointer to the thread's private data structure on success; NULL if thread ID is invalid or data not initialized
  33. *
  34. * @note
  35. * - Protects global thread table access with spinlock to prevent data race conditions
  36. * - Magic number validation (magic) prevents access to released or corrupted thread data
  37. * - Internal interface typically used by other POSIX thread library functions
  38. */
  39. _pthread_data_t *_pthread_get_data(pthread_t thread)
  40. {
  41. _pthread_data_t *ptd;
  42. if (thread >= PTHREAD_NUM_MAX) return NULL;
  43. rt_hw_spin_lock(&pth_lock);
  44. ptd = pth_table[thread];
  45. rt_hw_spin_unlock(&pth_lock);
  46. if (ptd && ptd->magic == PTHREAD_MAGIC) return ptd;
  47. return NULL;
  48. }
  49. /**
  50. * @brief Get the index position of a thread data in the global thread table
  51. *
  52. * This function searches for matching thread data index by traversing the global thread table.
  53. * Uses spinlock synchronization mechanism to ensure safe access to the global thread table
  54. * in multi-threaded environments.
  55. *
  56. * @param ptd Pointer to the target thread data structure
  57. *
  58. * @return Index value of type pthread_t
  59. * - Returns corresponding index (0~PTHREAD_NUM_MAX-1) when found
  60. * - Returns PTHREAD_NUM_MAX when no match is found
  61. *
  62. * @note
  63. * - Protects global thread table access with spinlock to prevent data races from concurrent access
  64. * - Uses sequential traversal method to find matching thread data
  65. * - Return value of PTHREAD_NUM_MAX indicates no match found in the global table
  66. */
  67. pthread_t _pthread_data_get_pth(_pthread_data_t *ptd)
  68. {
  69. int index;
  70. rt_hw_spin_lock(&pth_lock);
  71. for (index = 0; index < PTHREAD_NUM_MAX; index ++)
  72. {
  73. if (pth_table[index] == ptd) break;
  74. }
  75. rt_hw_spin_unlock(&pth_lock);
  76. return index;
  77. }
  78. /**
  79. * @brief Create and initialize a new thread data structure with index allocation
  80. *
  81. * This function allocates memory for a new thread data structure, initializes its default state,
  82. * and registers it in the global thread table. Uses spinlock synchronization to ensure safe
  83. * access to the global thread table in multi-threaded environments.
  84. *
  85. * @return Allocated index value of type pthread_t
  86. * - Returns valid index (0~PTHREAD_NUM_MAX-1) on successful allocation
  87. * - Returns PTHREAD_NUM_MAX when memory allocation fails or no space available in thread table
  88. *
  89. * @note
  90. * - Protects global thread table access with spinlock to prevent data races
  91. * - Uses sequential search to find first available slot in thread table
  92. * - Cleans up allocated memory and returns error when no available slots
  93. * - Initializes thread data with default states:
  94. * - Cancellation disabled (PTHREAD_CANCEL_DISABLE)
  95. * - Deferred cancellation type (PTHREAD_CANCEL_DEFERRED)
  96. * - Magic number validation (PTHREAD_MAGIC) for structure integrity
  97. */
  98. pthread_t _pthread_data_create(void)
  99. {
  100. int index;
  101. _pthread_data_t *ptd = NULL;
  102. ptd = (_pthread_data_t*)rt_malloc(sizeof(_pthread_data_t));
  103. if (!ptd) return PTHREAD_NUM_MAX;
  104. memset(ptd, 0x0, sizeof(_pthread_data_t));
  105. ptd->canceled = 0;
  106. ptd->cancelstate = PTHREAD_CANCEL_DISABLE;
  107. ptd->canceltype = PTHREAD_CANCEL_DEFERRED;
  108. ptd->magic = PTHREAD_MAGIC;
  109. rt_hw_spin_lock(&pth_lock);
  110. for (index = 0; index < PTHREAD_NUM_MAX; index ++)
  111. {
  112. if (pth_table[index] == NULL)
  113. {
  114. pth_table[index] = ptd;
  115. break;
  116. }
  117. }
  118. rt_hw_spin_unlock(&pth_lock);
  119. /* full of pthreads, clean magic and release ptd */
  120. if (index == PTHREAD_NUM_MAX)
  121. {
  122. ptd->magic = 0x0;
  123. rt_free(ptd);
  124. }
  125. return index;
  126. }
  127. /**
  128. * @brief Destroy thread local storage item at specified index
  129. *
  130. * This function cleans up thread-local storage data by:
  131. * 1. Checking if the key at given index is active
  132. * 2. If TLS data exists and a destructor is registered, invoking the destructor
  133. * 3. Properly releasing resources associated with the TLS slot
  134. *
  135. * @param index Index into the thread keys array (0 to PTHREAD_KEY_MAX-1)
  136. * @param ptd Pointer to thread data structure containing TLS information
  137. *
  138. * @note
  139. * - Relies on external spinlock protection when accessing shared data
  140. * - Only processes valid keys that have been initialized
  141. * - Safely handles NULL pointers and missing destructors
  142. * - Designed to be called during thread cleanup or explicit TLS destruction
  143. * - Matches POSIX thread standard requirements for TLS destructor invocation
  144. */
  145. static inline void _destroy_item(int index, _pthread_data_t *ptd)
  146. {
  147. extern _pthread_key_data_t _thread_keys[PTHREAD_KEY_MAX];
  148. void *data;
  149. if (_thread_keys[index].is_used)
  150. {
  151. data = ptd->tls[index];
  152. if (data && _thread_keys[index].destructor)
  153. {
  154. _thread_keys[index].destructor(data);
  155. }
  156. }
  157. }
  158. #ifdef RT_USING_CPLUSPLUS11
  159. #define NOT_USE_CXX_TLS -1
  160. #endif
  161. /**
  162. * @brief Destroy and clean up a thread data structure along with associated resources
  163. *
  164. * This function releases all resources associated with a thread data structure including:
  165. * - Thread-local storage (TLS) destructors execution
  166. * - Joinable semaphore deletion
  167. * - Global thread table entry cleanup
  168. * - Memory deallocation after proper resource release
  169. *
  170. * @param ptd Pointer to the thread data structure to be destroyed
  171. *
  172. * @note
  173. * - Protects global thread table access with spinlock to prevent data races
  174. * - Handles TLS destruction differently based on C++11 support:
  175. * - C++11: Reverse iteration from emutls key position for safe destructor calls
  176. * - C-only: Forward iteration through all thread keys
  177. * - Maintains strict resource cleanup order:
  178. * 1. TLS destructors -> 2. Global table removal -> 3. Semaphore deletion -> 4. Memory release
  179. * - Uses magic number validation to prevent double-free and invalid access
  180. * - Explicitly clears magic number before final memory release
  181. * - Nullifies pointer references after freeing to prevent dangling references
  182. * - Thread-safe operation through spinlock protection during critical sections
  183. */
  184. void _pthread_data_destroy(_pthread_data_t *ptd)
  185. {
  186. pthread_t pth;
  187. if (ptd)
  188. {
  189. /* if this thread create the local thread data,
  190. * destruct thread local key
  191. */
  192. if (ptd->tls != RT_NULL)
  193. {
  194. int index;
  195. #ifdef RT_USING_CPLUSPLUS11
  196. /* If C++11 is enabled and emutls is used,
  197. * destructors of C++ object must be called safely.
  198. */
  199. extern pthread_key_t emutls_get_pthread_key(void);
  200. pthread_key_t emutls_pthread_key = emutls_get_pthread_key();
  201. if (emutls_pthread_key != NOT_USE_CXX_TLS)
  202. {
  203. /* If execution reaches here, C++ 'thread_local' may be used.
  204. * Destructors of c++ class object must be called before emutls_key_destructor.
  205. */
  206. int start = ((emutls_pthread_key - 1 + PTHREAD_KEY_MAX) % PTHREAD_KEY_MAX);
  207. int i = 0;
  208. for (index = start; i < PTHREAD_KEY_MAX; index = (index - 1 + PTHREAD_KEY_MAX) % PTHREAD_KEY_MAX, i ++)
  209. {
  210. _destroy_item(index, ptd);
  211. }
  212. }
  213. else
  214. #endif
  215. {
  216. /* If only C TLS is used, that is, POSIX TLS or __Thread_local,
  217. * just iterate the _thread_keys from index 0.
  218. */
  219. for (index = 0; index < PTHREAD_KEY_MAX; index ++)
  220. {
  221. _destroy_item(index, ptd);
  222. }
  223. }
  224. /* release tls area */
  225. rt_free(ptd->tls);
  226. ptd->tls = RT_NULL;
  227. }
  228. pth = _pthread_data_get_pth(ptd);
  229. /* remove from pthread table */
  230. rt_hw_spin_lock(&pth_lock);
  231. pth_table[pth] = NULL;
  232. rt_hw_spin_unlock(&pth_lock);
  233. /* delete joinable semaphore */
  234. if (ptd->joinable_sem != RT_NULL)
  235. {
  236. rt_sem_delete(ptd->joinable_sem);
  237. ptd->joinable_sem = RT_NULL;
  238. }
  239. /* clean magic */
  240. ptd->magic = 0x0;
  241. /* free ptd */
  242. rt_free(ptd);
  243. }
  244. }
  245. /**
  246. * @brief Perform final cleanup of thread resources during thread termination
  247. *
  248. * This function handles the complete resource cleanup for a terminated thread, including:
  249. * - Clearing cleanup handlers
  250. * - Releasing thread stack memory
  251. * - Detaching thread data structures
  252. * - Final deallocation of thread control block
  253. *
  254. * @param tid Thread control block pointer to be cleaned up
  255. *
  256. * @note
  257. * - Must be called as the final cleanup step after thread termination
  258. * - Follows strict resource release order:
  259. * 1. Clear cleanup handlers -> 2. Release stack -> 3. Detach data -> 4. Free control block
  260. * - Explicitly nullifies pointers after freeing to prevent dangling references
  261. * - Thread-safe operation assumes caller has handled synchronization
  262. * - Handles both joinable and detached thread cleanup scenarios
  263. * - Designed to work with thread detachment and join completion mechanisms
  264. */
  265. static void _pthread_cleanup(rt_thread_t tid)
  266. {
  267. /* clear cleanup function */
  268. tid->cleanup = RT_NULL;
  269. /* restore tid stack */
  270. rt_free(tid->stack_addr);
  271. /* clear the "ptd->tid->pthread_data" */
  272. tid->pthread_data = RT_NULL;
  273. /* restore tid control block */
  274. rt_free(tid);
  275. }
  276. /**
  277. * @brief Thread entry point stub that manages thread execution and resource cleanup
  278. *
  279. * This function serves as the entry point for POSIX threads, executing the thread's main
  280. * function and handling post-exit resource management based on the thread's detach state.
  281. *
  282. * @param parameter Thread parameter containing the _pthread_data_t structure pointer
  283. *
  284. * @note
  285. * - Executes thread's main function through thread_entry callback
  286. * - Handles two resource management scenarios:
  287. * - JOINABLE threads: Store return value and release join semaphore
  288. * - DETACHED threads: Immediately destroy thread resources
  289. * - Maintains strict execution flow:
  290. * 1. Execute user thread function -> 2. Check detach state -> 3. Handle cleanup
  291. * - Properly coordinates with joinable semaphore mechanism for synchronous termination
  292. * - Assumes thread data structure remains valid until cleanup completion
  293. * - Thread-safe operation relies on proper synchronization in resource destruction
  294. * - Integrates with pthread lifecycle management system for complete resource recovery
  295. */
  296. static void pthread_entry_stub(void *parameter)
  297. {
  298. void *value;
  299. _pthread_data_t *ptd;
  300. ptd = (_pthread_data_t *)parameter;
  301. /* execute pthread entry */
  302. value = ptd->thread_entry(ptd->thread_parameter);
  303. /* According to "detachstate" to whether or not to recycle resource immediately */
  304. if (ptd->attr.detachstate == PTHREAD_CREATE_JOINABLE)
  305. {
  306. /* set value */
  307. ptd->return_value = value;
  308. rt_sem_release(ptd->joinable_sem);
  309. }
  310. else
  311. {
  312. /* release pthread resource */
  313. _pthread_data_destroy(ptd);
  314. }
  315. }
  316. /**
  317. * @brief Creates a new thread in a POSIX-compliant system.
  318. *
  319. * The `pthread_create` function initializes a new thread in the calling process. The new thread starts execution
  320. * by invoking the function specified by the `start` parameter. The thread runs concurrently with the calling thread.
  321. *
  322. * @param[out] pid
  323. * A pointer to a `pthread_t` object where the ID of the newly created thread will be stored.
  324. * This ID can be used to refer to the thread in subsequent function calls.
  325. *
  326. * @param[in] attr
  327. * A pointer to a `pthread_attr_t` object that specifies attributes for the new thread, or `NULL` for default attributes.
  328. * Default attributes include:
  329. * - Detached state: joinable.
  330. * - Stack size: implementation-defined default.
  331. *
  332. * @param[in] start
  333. * A pointer to the function that the new thread will execute. This function must have the following signature:
  334. * `void *start(void *parameter)`.
  335. *
  336. * @param[in] parameter
  337. * A pointer to data passed as an argument to the `start` function. The meaning and handling of this data is determined
  338. * by the `start` function.
  339. *
  340. * @return
  341. * Returns 0 on success. On failure, a non-zero error code is returned, indicating the error condition:
  342. * - `EAGAIN`: Insufficient resources to create another thread.
  343. * - `EINVAL`: Invalid attributes specified in `attr`.
  344. * - `EPERM`: Insufficient permissions to set the requested attributes.
  345. *
  346. * @note
  347. * It is the caller's responsibility to manage the lifetime of any resources associated with the new thread.
  348. * If the thread is not detached, it must be joined using `pthread_join` to avoid resource leaks.
  349. *
  350. * @see pthread_join, pthread_exit, pthread_attr_init
  351. */
  352. int pthread_create(pthread_t *pid,
  353. const pthread_attr_t *attr,
  354. void *(*start)(void *), void *parameter)
  355. {
  356. int ret = 0;
  357. void *stack;
  358. char name[RT_NAME_MAX];
  359. static rt_uint16_t pthread_number = 0;
  360. pthread_t pth_id;
  361. _pthread_data_t *ptd;
  362. /* pid shall be provided */
  363. RT_ASSERT(pid != RT_NULL);
  364. /* allocate posix thread data */
  365. pth_id = _pthread_data_create();
  366. if (pth_id == PTHREAD_NUM_MAX)
  367. {
  368. ret = ENOMEM;
  369. goto __exit;
  370. }
  371. /* get pthread data */
  372. ptd = _pthread_get_data(pth_id);
  373. RT_ASSERT(ptd != RT_NULL);
  374. if (attr != RT_NULL)
  375. {
  376. ptd->attr = *attr;
  377. }
  378. else
  379. {
  380. /* use default attribute */
  381. pthread_attr_init(&ptd->attr);
  382. }
  383. if (ptd->attr.stacksize == 0)
  384. {
  385. ret = EINVAL;
  386. goto __exit;
  387. }
  388. rt_snprintf(name, sizeof(name), "pth%02d", pthread_number ++);
  389. /* pthread is a static thread object */
  390. ptd->tid = (rt_thread_t) rt_malloc(sizeof(struct rt_thread));
  391. if (ptd->tid == RT_NULL)
  392. {
  393. ret = ENOMEM;
  394. goto __exit;
  395. }
  396. memset(ptd->tid, 0, sizeof(struct rt_thread));
  397. if (ptd->attr.detachstate == PTHREAD_CREATE_JOINABLE)
  398. {
  399. ptd->joinable_sem = rt_sem_create(name, 0, RT_IPC_FLAG_FIFO);
  400. if (ptd->joinable_sem == RT_NULL)
  401. {
  402. ret = ENOMEM;
  403. goto __exit;
  404. }
  405. }
  406. else
  407. {
  408. ptd->joinable_sem = RT_NULL;
  409. }
  410. /* set parameter */
  411. ptd->thread_entry = start;
  412. ptd->thread_parameter = parameter;
  413. /* stack */
  414. if (ptd->attr.stackaddr == 0)
  415. {
  416. stack = (void *)rt_malloc(ptd->attr.stacksize);
  417. }
  418. else
  419. {
  420. stack = (void *)(ptd->attr.stackaddr);
  421. }
  422. if (stack == RT_NULL)
  423. {
  424. ret = ENOMEM;
  425. goto __exit;
  426. }
  427. /* initial this pthread to system */
  428. if (rt_thread_init(ptd->tid, name, pthread_entry_stub, ptd,
  429. stack, ptd->attr.stacksize,
  430. ptd->attr.schedparam.sched_priority, 20) != RT_EOK)
  431. {
  432. ret = EINVAL;
  433. goto __exit;
  434. }
  435. /* set pthread id */
  436. *pid = pth_id;
  437. /* set pthread cleanup function and ptd data */
  438. ptd->tid->cleanup = _pthread_cleanup;
  439. ptd->tid->pthread_data = (void *)ptd;
  440. /* start thread */
  441. if (rt_thread_startup(ptd->tid) == RT_EOK)
  442. return 0;
  443. /* start thread failed */
  444. rt_thread_detach(ptd->tid);
  445. ret = EINVAL;
  446. __exit:
  447. if (pth_id != PTHREAD_NUM_MAX)
  448. {
  449. _pthread_data_destroy(ptd);
  450. }
  451. return ret;
  452. }
  453. RTM_EXPORT(pthread_create);
  454. /**
  455. * @brief Marks a thread as detached, allowing its resources to be automatically released upon termination.
  456. *
  457. * The `pthread_detach` function separates the specified thread from the calling thread. Once a thread is detached,
  458. * its resources will be automatically reclaimed by the system upon the thread's termination. A detached thread cannot
  459. * be joined using `pthread_join`.
  460. *
  461. * @param[in] thread
  462. * The thread ID of the thread to be detached. This must be a valid thread ID returned by `pthread_create`.
  463. *
  464. * @return
  465. * Returns 0 on success. On failure, an error code is returned:
  466. * - `EINVAL`: The specified thread is not joinable or is already detached.
  467. * - `ESRCH`: No thread with the specified ID could be found.
  468. *
  469. * @note
  470. * - Detaching a thread allows it to run independently. Once detached, the thread's termination status cannot
  471. * be retrieved, and it cannot be joined.
  472. * - Threads can be created in a detached state using attributes set with `pthread_attr_setdetachstate`.
  473. *
  474. * @see pthread_create, pthread_join, pthread_attr_setdetachstate
  475. */
  476. int pthread_detach(pthread_t thread)
  477. {
  478. int ret = 0;
  479. _pthread_data_t *ptd = _pthread_get_data(thread);
  480. if (ptd == RT_NULL)
  481. {
  482. /* invalid pthread id */
  483. ret = EINVAL;
  484. goto __exit;
  485. }
  486. if (ptd->attr.detachstate == PTHREAD_CREATE_DETACHED)
  487. {
  488. /* The implementation has detected that the value specified by thread does not refer
  489. * to a joinable thread.
  490. */
  491. ret = EINVAL;
  492. goto __exit;
  493. }
  494. if ((RT_SCHED_CTX(ptd->tid).stat & RT_THREAD_STAT_MASK) == RT_THREAD_CLOSE)
  495. {
  496. /* destroy this pthread */
  497. _pthread_data_destroy(ptd);
  498. goto __exit;
  499. }
  500. else
  501. {
  502. /* change to detach state */
  503. ptd->attr.detachstate = PTHREAD_CREATE_DETACHED;
  504. /* detach joinable semaphore */
  505. if (ptd->joinable_sem)
  506. {
  507. rt_sem_delete(ptd->joinable_sem);
  508. ptd->joinable_sem = RT_NULL;
  509. }
  510. }
  511. __exit:
  512. return ret;
  513. }
  514. RTM_EXPORT(pthread_detach);
  515. /**
  516. * @brief Waits for the specified thread to terminate and retrieves its exit status.
  517. *
  518. * The `pthread_join` function blocks the calling thread until the specified thread terminates.
  519. * If the specified thread has already terminated, it returns immediately. The exit status of
  520. * the terminated thread can optionally be retrieved via the `value_ptr` parameter.
  521. *
  522. * @param[in] thread
  523. * The thread ID of the thread to wait for. This must be a joinable thread created with `pthread_create`.
  524. *
  525. * @param[out] value_ptr
  526. * A pointer to a location where the exit status of the terminated thread will be stored.
  527. * If the thread terminated by calling `pthread_exit`, the value passed to `pthread_exit`
  528. * will be stored at this location. If this parameter is `NULL`, the exit status is ignored.
  529. *
  530. * @return
  531. * Returns 0 on success. On failure, an error code is returned:
  532. * - `ESRCH`: The specified thread does not exist.
  533. * - `EINVAL`: The specified thread is not joinable.
  534. * - `EDEADLK`: A deadlock was detected (e.g., a thread tries to join itself).
  535. *
  536. * @note
  537. * - Threads must not be detached to use `pthread_join`.
  538. * - If `pthread_join` is not called for joinable threads, their resources are not released, leading to resource leaks.
  539. *
  540. * @see pthread_create, pthread_exit, pthread_detach
  541. */
  542. int pthread_join(pthread_t thread, void **value_ptr)
  543. {
  544. _pthread_data_t *ptd;
  545. rt_err_t result;
  546. ptd = _pthread_get_data(thread);
  547. if (ptd == RT_NULL)
  548. {
  549. return EINVAL; /* invalid pthread id */
  550. }
  551. if (ptd->tid == rt_thread_self())
  552. {
  553. /* join self */
  554. return EDEADLK;
  555. }
  556. if (ptd->attr.detachstate == PTHREAD_CREATE_DETACHED)
  557. {
  558. return EINVAL; /* join on a detached pthread */
  559. }
  560. result = rt_sem_take(ptd->joinable_sem, RT_WAITING_FOREVER);
  561. if (result == RT_EOK)
  562. {
  563. /* get return value */
  564. if (value_ptr != RT_NULL)
  565. *value_ptr = ptd->return_value;
  566. /* destroy this pthread */
  567. _pthread_data_destroy(ptd);
  568. }
  569. else
  570. {
  571. return ESRCH;
  572. }
  573. return 0;
  574. }
  575. RTM_EXPORT(pthread_join);
  576. /**
  577. * @brief Returns the thread ID of the calling thread.
  578. *
  579. * The `pthread_self` function returns the thread ID of the calling thread. The thread ID is unique to the
  580. * thread within a process and can be used to identify the calling thread in the context of multithreading.
  581. *
  582. * The value returned by `pthread_self` can be compared with the thread IDs of other threads to determine
  583. * if two threads are the same.
  584. *
  585. * @return
  586. * The thread ID of the calling thread.
  587. *
  588. * @note
  589. * - The thread ID returned by `pthread_self` is not the same as the operating system's thread ID.
  590. * - This function does not affect the calling thread's state or execution.
  591. * - The thread ID returned by `pthread_self` is only meaningful in the context of the current process.
  592. *
  593. * @see pthread_create, pthread_equal, pthread_join
  594. */
  595. pthread_t pthread_self (void)
  596. {
  597. rt_thread_t tid;
  598. _pthread_data_t *ptd;
  599. tid = rt_thread_self();
  600. if (tid == NULL) return PTHREAD_NUM_MAX;
  601. /* get pthread data from pthread_data of thread */
  602. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  603. RT_ASSERT(ptd != RT_NULL);
  604. return _pthread_data_get_pth(ptd);
  605. }
  606. RTM_EXPORT(pthread_self);
  607. /**
  608. * @brief Retrieves the clock ID for the specified thread.
  609. *
  610. * The `pthread_getcpuclockid` function retrieves the clock ID associated with the CPU time used
  611. * by the specified thread.
  612. *
  613. * @param[in] thread
  614. * The thread whose CPU clock ID is to be retrieved. If the thread is the calling thread,
  615. * the current thread's ID is used.
  616. *
  617. * @param[out] clock_id
  618. * A pointer to a `clockid_t` variable that will be filled with the clock ID associated
  619. * with the specified thread.
  620. *
  621. * @return
  622. * - `0` on success.
  623. * - `EINVAL` if the `thread` is not a valid thread identifier.
  624. * - `ESRCH` if the specified thread does not exist.
  625. *
  626. * @note
  627. * The clock returned by this function is specific to the thread and is different from the
  628. * system-wide clock. It measures the CPU time consumed by the specified thread, not wall-clock
  629. * time. The thread's CPU time can be obtained using `clock_gettime` with the returned `clock_id`.
  630. *
  631. * @see clock_gettime, pthread_create, pthread_self
  632. */
  633. int pthread_getcpuclockid(pthread_t thread, clockid_t *clock_id)
  634. {
  635. if(_pthread_get_data(thread) == NULL)
  636. {
  637. return EINVAL;
  638. }
  639. *clock_id = (clockid_t)rt_tick_get();
  640. return 0;
  641. }
  642. RTM_EXPORT(pthread_getcpuclockid);
  643. /**
  644. * @brief Retrieves the current concurrency level of the program.
  645. *
  646. * The `pthread_getconcurrency` function returns the current concurrency level of the program.
  647. * This value represents the number of threads that can run concurrently in the program,
  648. * based on the current settings of the pthreads library. It is used to help tune the behavior
  649. * of thread scheduling in some systems.
  650. *
  651. * @return
  652. * The current concurrency level of the program.
  653. * - The value is an integer representing the number of threads that are permitted to run
  654. * concurrently in the system, based on the library's current configuration.
  655. * - A return value of `0` typically means that the system is using the default concurrency
  656. * level, which may be determined automatically by the system or by thread creation behavior.
  657. *
  658. * @note
  659. * - The behavior and meaning of concurrency levels can be implementation-dependent,
  660. * and it may vary across different systems or environments.
  661. * - The function is typically used for diagnostic purposes, and its behavior may not
  662. * affect thread execution directly.
  663. *
  664. * @see pthread_setconcurrency
  665. */
  666. int pthread_getconcurrency(void)
  667. {
  668. return concurrency_level;
  669. }
  670. RTM_EXPORT(pthread_getconcurrency);
  671. /**
  672. * @brief Sets the concurrency level of the program.
  673. *
  674. * The `pthread_setconcurrency` function sets the number of threads that are allowed to run concurrently.
  675. * The concurrency level defines the maximum number of threads that can be executed in parallel by the system.
  676. * This is useful for tuning thread behavior and controlling system resource usage, especially in environments
  677. * with limited resources (e.g., CPU cores).
  678. *
  679. * @param[in] new_level
  680. * The new concurrency level to be set. This value represents the number of threads that can execute concurrently.
  681. * - A value of `0` typically means that the system will automatically determine the concurrency level based on
  682. * the system's configuration and available resources.
  683. * - A non-zero value explicitly sets the maximum number of threads that can run concurrently.
  684. *
  685. * @return
  686. * - `0` on success.
  687. * - `EINVAL` if the `new_level` is invalid or if the system does not support this functionality.
  688. *
  689. * @note
  690. * - The behavior of this function is system-dependent. Some systems may ignore the concurrency setting
  691. * and automatically manage the concurrency based on available resources (e.g., CPU cores).
  692. * - This function may not have any effect on systems that do not support concurrency settings at the library level.
  693. * - The concurrency level controls thread scheduling policies and is intended to influence how the thread library
  694. * manages threads, not how the operating system schedules them at the kernel level.
  695. *
  696. * @see pthread_getconcurrency
  697. */
  698. int pthread_setconcurrency(int new_level)
  699. {
  700. concurrency_level = new_level;
  701. return 0;
  702. }
  703. RTM_EXPORT(pthread_setconcurrency);
  704. /**
  705. * @brief Retrieves the scheduling policy and parameters of a thread.
  706. *
  707. * The `pthread_getschedparam` function retrieves the scheduling policy and the scheduling parameters
  708. * (such as priority) for the specified thread. This allows you to check the scheduling settings of a thread
  709. * and can be useful for thread management and performance tuning in a multithreaded application.
  710. *
  711. * @param[in] thread
  712. * The thread whose scheduling policy and parameters are to be retrieved. This is typically a valid
  713. * `pthread_t` identifier of a thread that has already been created.
  714. *
  715. * @param[out] policy
  716. * A pointer to an integer where the scheduling policy of the specified thread will be stored. The
  717. * value will be one of the following constants defined in `<sched.h>`:
  718. * - `SCHED_FIFO`: First-in, first-out scheduling policy.
  719. * - `SCHED_RR`: Round-robin scheduling policy.
  720. * - `SCHED_OTHER`: Default policy, which is typically used by non-realtime threads.
  721. * - `SCHED_IDLE`: For idle threads (system-level threads that do minimal work).
  722. * - `SCHED_BATCH`: For threads that should be scheduled with lower priority than interactive threads.
  723. * - `SCHED_DEADLINE`: A policy that allows specifying real-time deadlines (on systems that support it).
  724. *
  725. * @param[out] param
  726. * A pointer to a `struct sched_param` where the scheduling parameters (e.g., priority) for the thread
  727. * will be stored. The `sched_param` structure typically contains:
  728. * - `sched_priority`: The priority value associated with the thread's scheduling policy.
  729. *
  730. * @return
  731. * - `0` on success.
  732. * - `ESRCH` if the specified thread does not exist.
  733. * - `EINVAL` if an invalid argument is provided, such as an invalid thread ID or null pointers for the policy or parameters.
  734. *
  735. * @note
  736. * - This function retrieves the current scheduling settings for a thread. These settings can be used
  737. * to monitor or adjust thread behavior.
  738. * - The scheduling policies and priorities may be platform-dependent and subject to system configuration.
  739. *
  740. * @see pthread_setschedparam, sched_getparam
  741. */
  742. int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param)
  743. {
  744. _pthread_data_t *ptd;
  745. ptd = _pthread_get_data(thread);
  746. pthread_attr_getschedpolicy(&ptd->attr, policy);
  747. pthread_attr_getschedparam(&ptd->attr, param);
  748. return 0;
  749. }
  750. RTM_EXPORT(pthread_getschedparam);
  751. /**
  752. * @brief Sets the scheduling policy and parameters for a thread.
  753. *
  754. * The `pthread_setschedparam` function sets the scheduling policy and scheduling parameters (such as priority)
  755. * for the specified thread. This allows you to control how the thread is scheduled by the operating system.
  756. * It is useful for adjusting thread behavior, especially for real-time or performance-sensitive applications.
  757. *
  758. * @param[in] thread
  759. * The thread whose scheduling policy and parameters are to be set. This is a valid `pthread_t` identifier.
  760. *
  761. * @param[in] policy
  762. * The scheduling policy to be set for the thread. This can be one of the following values:
  763. * - `SCHED_FIFO`: First-in, first-out scheduling policy, where threads are scheduled based on their arrival time.
  764. * - `SCHED_RR`: Round-robin scheduling policy, where each thread is allocated a fixed time slice and scheduled cyclically.
  765. * - `SCHED_OTHER`: Default policy for non-realtime threads.
  766. * - `SCHED_IDLE`: For threads intended to run only when no other threads are runnable.
  767. * - `SCHED_BATCH`: For threads that should run with lower priority than interactive threads.
  768. * - `SCHED_DEADLINE`: For real-time threads that have a specified deadline (if supported).
  769. *
  770. * @param[in] param
  771. * A pointer to a `struct sched_param`, which contains the scheduling parameters, typically the thread's priority.
  772. * The `sched_priority` field is the most commonly used parameter, and it controls the thread's priority within
  773. * the specified scheduling policy.
  774. *
  775. * @return
  776. * - `0` on success.
  777. * - `EINVAL` if an invalid policy or parameter is provided.
  778. * - `ESRCH` if the specified thread does not exist.
  779. * - `EPERM` if the caller does not have permission to modify the thread's scheduling attributes.
  780. *
  781. * @note
  782. * - The `sched_param` structure's `sched_priority` field specifies the priority of the thread. The priority
  783. * range depends on the policy used. For example, for `SCHED_FIFO` and `SCHED_RR`, higher priority values
  784. * correspond to higher priority threads, while for `SCHED_OTHER`, priorities are not as strictly enforced.
  785. * - Changing a thread's scheduling parameters may affect its execution behavior, including how it competes with
  786. * other threads for CPU time.
  787. * - The system may not allow you to modify scheduling parameters for all threads, depending on system configuration
  788. * and privileges.
  789. *
  790. * @see pthread_getschedparam
  791. */
  792. int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param)
  793. {
  794. _pthread_data_t *ptd;
  795. ptd = _pthread_get_data(thread);
  796. pthread_attr_setschedpolicy(&ptd->attr, policy);
  797. pthread_attr_setschedparam(&ptd->attr, param);
  798. return 0;
  799. }
  800. RTM_EXPORT(pthread_setschedparam);
  801. /**
  802. * @brief Sets the scheduling priority for a thread.
  803. *
  804. * The `pthread_setschedprio` function adjusts the priority of the specified thread while leaving its
  805. * scheduling policy unchanged. This is useful for fine-tuning thread behavior in multithreaded applications.
  806. *
  807. * @param[in] thread
  808. * The thread whose scheduling priority is to be changed. This must be a valid `pthread_t` identifier.
  809. *
  810. * @param[in] prio
  811. * The new scheduling priority for the thread. The priority must fall within the valid range for the
  812. * thread's current scheduling policy, as defined by `sched_get_priority_min` and `sched_get_priority_max`.
  813. *
  814. * @return
  815. * - `0` on success.
  816. * - `EINVAL` if the specified priority is invalid for the thread's current scheduling policy.
  817. * - `ESRCH` if the specified thread does not exist.
  818. * - `EPERM` if the calling process lacks the necessary privileges to set the thread's priority.
  819. *
  820. * @note
  821. * - Changing a thread's priority may require elevated privileges (e.g., root) on certain systems, especially
  822. * for real-time priorities.
  823. * - The priority range and behavior depend on the thread's current scheduling policy. For example:
  824. * - `SCHED_FIFO` and `SCHED_RR`: Priorities are used for strict scheduling.
  825. * - `SCHED_OTHER`: Priorities may have minimal or no effect.
  826. * - The behavior of this function is platform-dependent and may vary between different operating systems.
  827. *
  828. * @see pthread_setschedparam, pthread_getschedparam
  829. */
  830. int pthread_setschedprio(pthread_t thread, int prio)
  831. {
  832. _pthread_data_t *ptd;
  833. struct sched_param param;
  834. ptd = _pthread_get_data(thread);
  835. param.sched_priority = prio;
  836. pthread_attr_setschedparam(&ptd->attr, &param);
  837. return 0;
  838. }
  839. RTM_EXPORT(pthread_setschedprio);
  840. /**
  841. * @brief Terminates the calling thread and optionally returns a value.
  842. *
  843. * The `pthread_exit` function terminates the calling thread. It can optionally provide an exit status that can be
  844. * retrieved by other threads that join the calling thread using `pthread_join`. If the thread is detached, the
  845. * exit status is ignored and the system automatically reclaims resources once the thread terminates.
  846. *
  847. * @param[in] value
  848. * A pointer to a value that will be returned to any thread that calls `pthread_join` on this thread.
  849. * If `NULL`, no value is returned.
  850. *
  851. * @note
  852. * - This function does not terminate the process. It only terminates the calling thread.
  853. * - If the calling thread is the main thread, `pthread_exit` allows other threads to continue execution.
  854. * - If a thread terminates without calling `pthread_exit`, it returns control to the system when the thread's function ends.
  855. *
  856. * @see pthread_join, pthread_create
  857. */
  858. void pthread_exit(void *value)
  859. {
  860. _pthread_data_t *ptd;
  861. _pthread_cleanup_t *cleanup;
  862. rt_thread_t tid;
  863. if (rt_thread_self() == RT_NULL)
  864. {
  865. return;
  866. }
  867. /* get pthread data from pthread_data of thread */
  868. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  869. rt_enter_critical();
  870. /* disable cancel */
  871. ptd->cancelstate = PTHREAD_CANCEL_DISABLE;
  872. /* set return value */
  873. ptd->return_value = value;
  874. rt_exit_critical();
  875. /*
  876. * When use pthread_exit to exit.
  877. * invoke pushed cleanup
  878. */
  879. while (ptd->cleanup != RT_NULL)
  880. {
  881. cleanup = ptd->cleanup;
  882. ptd->cleanup = cleanup->next;
  883. cleanup->cleanup_func(cleanup->parameter);
  884. /* release this cleanup function */
  885. rt_free(cleanup);
  886. }
  887. /* get the info aboult "tid" early */
  888. tid = ptd->tid;
  889. /* According to "detachstate" to whether or not to recycle resource immediately */
  890. if (ptd->attr.detachstate == PTHREAD_CREATE_JOINABLE)
  891. {
  892. /* set value */
  893. rt_sem_release(ptd->joinable_sem);
  894. }
  895. else
  896. {
  897. /* release pthread resource */
  898. _pthread_data_destroy(ptd);
  899. }
  900. /*
  901. * second: detach thread.
  902. * this thread will be removed from scheduler list
  903. * and because there is a cleanup function in the
  904. * thread (pthread_cleanup), it will move to defunct
  905. * thread list and wait for handling in idle thread.
  906. */
  907. rt_thread_detach(tid);
  908. /* reschedule thread */
  909. rt_schedule();
  910. }
  911. RTM_EXPORT(pthread_exit);
  912. /**
  913. * @brief Executes a routine once in a multithreaded environment.
  914. *
  915. * The `pthread_once` function ensures that the specified initialization routine is executed exactly once,
  916. * even if multiple threads attempt to execute it simultaneously. It is typically used for one-time
  917. * initialization tasks in a multithreaded program.
  918. *
  919. * @param[in] once_control
  920. * A pointer to a `pthread_once_t` control variable. The init_routine can only be excuted
  921. * when (*once_control) is zero.
  922. *
  923. * @param[in] init_routine
  924. * A pointer to the initialization routine to be executed. This routine takes no arguments and
  925. * returns no value. It is guaranteed to be executed exactly once.
  926. *
  927. * @return
  928. * - `0` on success.
  929. *
  930. * @note
  931. * - The `pthread_once` function is thread-safe and guarantees that the `init_routine` is called only once.
  932. * - The `once_control` variable must remain valid and should not be modified by the application after
  933. * initialization.
  934. * - If the initialization routine fails or encounters an error, it is the responsibility of the routine
  935. * to handle it appropriately.
  936. *
  937. * @see pthread_mutex_lock, pthread_mutex_unlock
  938. */
  939. int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
  940. {
  941. RT_ASSERT(once_control != RT_NULL);
  942. RT_ASSERT(init_routine != RT_NULL);
  943. rt_enter_critical();
  944. if (!(*once_control))
  945. {
  946. /* call routine once */
  947. *once_control = 1;
  948. rt_exit_critical();
  949. init_routine();
  950. }
  951. rt_exit_critical();
  952. return 0;
  953. }
  954. RTM_EXPORT(pthread_once);
  955. int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void))
  956. {
  957. return EOPNOTSUPP;
  958. }
  959. RTM_EXPORT(pthread_atfork);
  960. /**
  961. * @brief Sends a signal to a specific thread.
  962. *
  963. * The `pthread_kill` function sends the specified signal to the target thread. This allows fine-grained
  964. * control over signal handling in multithreaded applications.
  965. *
  966. * @param[in] thread
  967. * The target thread to which the signal is sent. This is a valid `pthread_t` identifier.
  968. *
  969. * @param[in] sig
  970. * The signal to be sent. This can be any valid signal, such as those defined in `<signal.h>`. For example:
  971. * - `SIGTERM`: Request thread termination.
  972. * - `SIGUSR1` or `SIGUSR2`: User-defined signals.
  973. * - `0`: Used to check if the thread is still valid without sending a signal.
  974. *
  975. * @return
  976. * - `0` on success.
  977. * - `ESRCH` if the specified thread does not exist or is invalid.
  978. * - `EINVAL` if the signal number `sig` is invalid.
  979. *
  980. * @note
  981. * - The signal is delivered to the specified thread only if the thread has the appropriate signal handlers
  982. * set up. Unhandled signals might result in the default action for that signal.
  983. * - If `sig` is `0`, no signal is sent, but the function checks if the thread is valid and exists.
  984. * - Signal handling behavior is shared across threads in a process. For example, blocking or ignoring a signal
  985. * in one thread affects the entire process.
  986. *
  987. * @see pthread_sigmask, sigaction
  988. */
  989. int pthread_kill(pthread_t thread, int sig)
  990. {
  991. #ifdef RT_USING_SIGNALS
  992. _pthread_data_t *ptd;
  993. int ret;
  994. ptd = _pthread_get_data(thread);
  995. if (ptd)
  996. {
  997. ret = rt_thread_kill(ptd->tid, sig);
  998. if (ret == -RT_EINVAL)
  999. {
  1000. return EINVAL;
  1001. }
  1002. return ret;
  1003. }
  1004. return ESRCH;
  1005. #else
  1006. return ENOSYS;
  1007. #endif
  1008. }
  1009. RTM_EXPORT(pthread_kill);
  1010. #ifdef RT_USING_SIGNALS
  1011. /**
  1012. * @brief Modifies or retrieves the signal mask of the calling thread.
  1013. *
  1014. * The `pthread_sigmask` function allows a thread to block, unblock, or examine the signals in its signal mask.
  1015. * Signals that are blocked are not delivered to the thread until they are unblocked.
  1016. *
  1017. * @param[in] how
  1018. * Specifies how the signal mask is modified. Possible values:
  1019. * - `SIG_BLOCK`: Add the signals in `set` to the current signal mask.
  1020. * - `SIG_UNBLOCK`: Remove the signals in `set` from the current signal mask.
  1021. * - `SIG_SETMASK`: Replace the current signal mask with the signals in `set`.
  1022. *
  1023. * @param[in] set
  1024. * A pointer to a `sigset_t` containing the signals to be modified in the mask. Can be `NULL` if no change is needed.
  1025. *
  1026. * @param[out] oset
  1027. * A pointer to a `sigset_t` where the previous signal mask will be stored. Can be `NULL` if the previous mask is not required.
  1028. *
  1029. * @return
  1030. * - `0` on success.
  1031. *
  1032. * @note
  1033. * - Signal masks are thread-specific in a multithreaded program.
  1034. * - The `pthread_sigmask` function is designed for multithreaded programs, whereas `sigprocmask` should not be used.
  1035. * - Blocking a signal prevents it from being delivered to the thread until unblocked.
  1036. *
  1037. * @see sigprocmask, sigaction, pthread_kill
  1038. */
  1039. int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
  1040. {
  1041. return sigprocmask(how, set, oset);
  1042. }
  1043. #endif
  1044. /**
  1045. * @brief Unregisters a cleanup handler and optionally executes it.
  1046. *
  1047. * The `pthread_cleanup_pop` function unregisters a cleanup handler that was previously registered
  1048. * using `pthread_cleanup_push`. If the `execute` parameter is non-zero, the cleanup handler is executed
  1049. * at the point where the thread terminates or is canceled.
  1050. *
  1051. * If `execute` is zero, the handler is unregistered without being executed. This allows the handler
  1052. * to be removed from the cleanup stack without performing any actions.
  1053. *
  1054. * @param[in] execute
  1055. * If non-zero, the cleanup handler is executed when the thread terminates or is canceled.
  1056. * If zero, the handler is simply removed from the stack without executing it.
  1057. *
  1058. * @note
  1059. * - Cleanup handlers are executed in the reverse order of their registration (i.e., last-in, first-out).
  1060. * - It is important to use `pthread_cleanup_push` to register cleanup handlers and `pthread_cleanup_pop`
  1061. * to ensure they are properly unregistered and executed if needed.
  1062. * - This function should be paired with `pthread_cleanup_push` to manage cleanup handlers effectively.
  1063. *
  1064. * @see pthread_cleanup_push, pthread_exit, pthread_cancel
  1065. */
  1066. void pthread_cleanup_pop(int execute)
  1067. {
  1068. _pthread_data_t *ptd;
  1069. _pthread_cleanup_t *cleanup;
  1070. if (rt_thread_self() == NULL) return;
  1071. /* get pthread data from pthread_data of thread */
  1072. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  1073. RT_ASSERT(ptd != RT_NULL);
  1074. if (execute)
  1075. {
  1076. rt_enter_critical();
  1077. cleanup = ptd->cleanup;
  1078. if (cleanup)
  1079. ptd->cleanup = cleanup->next;
  1080. rt_exit_critical();
  1081. if (cleanup)
  1082. {
  1083. cleanup->cleanup_func(cleanup->parameter);
  1084. rt_free(cleanup);
  1085. }
  1086. }
  1087. }
  1088. RTM_EXPORT(pthread_cleanup_pop);
  1089. /**
  1090. * @brief Registers a cleanup handler to be executed when the calling thread terminates.
  1091. *
  1092. * The `pthread_cleanup_push` function registers a cleanup handler that is executed when the calling thread
  1093. * is canceled or exits (either normally or via `pthread_exit`). The cleanup handler will be executed
  1094. * in the reverse order of their registration.
  1095. *
  1096. * The cleanup handler can be used to release resources such as memory or file descriptors when the thread
  1097. * is terminated, whether it terminates normally or is canceled.
  1098. *
  1099. * @param[in] routine
  1100. * A pointer to the cleanup handler function. The function must have the following signature:
  1101. * `void routine(void* arg);`. It is invoked when the thread terminates or is canceled.
  1102. *
  1103. * @param[in] arg
  1104. * A pointer to the argument that will be passed to the cleanup handler (`routine`).
  1105. * This allows the handler to perform actions with the passed argument.
  1106. *
  1107. * @note
  1108. * - The cleanup handler is automatically invoked when a thread terminates or is canceled.
  1109. * - The cleanup handlers are executed in the reverse order of their registration, similar to how
  1110. * destructors are executed in a stack-based fashion.
  1111. * - `pthread_cleanup_pop` must be called to unregister the cleanup handler. It ensures that the handler
  1112. * is only invoked during the thread's termination process.
  1113. *
  1114. * @see pthread_cleanup_pop, pthread_cancel, pthread_exit
  1115. */
  1116. void pthread_cleanup_push(void (*routine)(void *), void *arg)
  1117. {
  1118. _pthread_data_t *ptd;
  1119. _pthread_cleanup_t *cleanup;
  1120. if (rt_thread_self() == NULL) return;
  1121. /* get pthread data from pthread_data of thread */
  1122. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  1123. RT_ASSERT(ptd != RT_NULL);
  1124. cleanup = (_pthread_cleanup_t *)rt_malloc(sizeof(_pthread_cleanup_t));
  1125. if (cleanup != RT_NULL)
  1126. {
  1127. cleanup->cleanup_func = routine;
  1128. cleanup->parameter = arg;
  1129. rt_enter_critical();
  1130. cleanup->next = ptd->cleanup;
  1131. ptd->cleanup = cleanup;
  1132. rt_exit_critical();
  1133. }
  1134. }
  1135. RTM_EXPORT(pthread_cleanup_push);
  1136. /*
  1137. * According to IEEE Std 1003.1, 2004 Edition , following pthreads
  1138. * interface support cancellation point:
  1139. * mq_receive()
  1140. * mq_send()
  1141. * mq_timedreceive()
  1142. * mq_timedsend()
  1143. * msgrcv()
  1144. * msgsnd()
  1145. * msync()
  1146. * pthread_cond_timedwait()
  1147. * pthread_cond_wait()
  1148. * pthread_join()
  1149. * pthread_testcancel()
  1150. * sem_timedwait()
  1151. * sem_wait()
  1152. *
  1153. * A cancellation point may also occur when a thread is
  1154. * executing the following functions:
  1155. * pthread_rwlock_rdlock()
  1156. * pthread_rwlock_timedrdlock()
  1157. * pthread_rwlock_timedwrlock()
  1158. * pthread_rwlock_wrlock()
  1159. *
  1160. * The pthread_cancel(), pthread_setcancelstate(), and pthread_setcanceltype()
  1161. * functions are defined to be async-cancel safe.
  1162. */
  1163. /**
  1164. * @brief Sets the cancelability state of the calling thread.
  1165. *
  1166. * The `pthread_setcancelstate` function allows a thread to enable or disable its ability to be canceled
  1167. * by another thread. Cancelability determines if and when a thread responds to a cancellation request.
  1168. *
  1169. * @param[in] state
  1170. * The new cancelability state for the calling thread. Possible values:
  1171. * - `PTHREAD_CANCEL_ENABLE`: The thread can be canceled.
  1172. * - `PTHREAD_CANCEL_DISABLE`: The thread cannot be canceled.
  1173. *
  1174. * @param[out] oldstate
  1175. * A pointer to an integer where the previous cancelability state will be stored. Can be `NULL` if
  1176. * the previous state is not needed.
  1177. *
  1178. * @return
  1179. * - `0` on success.
  1180. * - `EINVAL` if the `state` is not a valid cancelability state.
  1181. *
  1182. * @note
  1183. * - The cancelability state affects how the thread responds to cancellation requests:
  1184. * - In the `PTHREAD_CANCEL_DISABLE` state, cancellation requests are held pending until the state is changed to `PTHREAD_CANCEL_ENABLE`.
  1185. * - Cancelability is distinct from the cancelability type, which controls the timing of cancellation (deferred or asynchronous).
  1186. * - By default, threads are created with `PTHREAD_CANCEL_ENABLE`.
  1187. *
  1188. * @see pthread_cancel, pthread_setcanceltype
  1189. */
  1190. int pthread_setcancelstate(int state, int *oldstate)
  1191. {
  1192. _pthread_data_t *ptd;
  1193. if (rt_thread_self() == NULL) return EINVAL;
  1194. /* get pthread data from pthread_data of thread */
  1195. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  1196. RT_ASSERT(ptd != RT_NULL);
  1197. if ((state == PTHREAD_CANCEL_ENABLE) || (state == PTHREAD_CANCEL_DISABLE))
  1198. {
  1199. if (oldstate)
  1200. *oldstate = ptd->cancelstate;
  1201. ptd->cancelstate = state;
  1202. return 0;
  1203. }
  1204. return EINVAL;
  1205. }
  1206. RTM_EXPORT(pthread_setcancelstate);
  1207. /**
  1208. * @brief Sets the cancellation type of the calling thread.
  1209. *
  1210. * The `pthread_setcanceltype` function allows a thread to specify when it should respond to
  1211. * a cancellation request. The cancellation type can be set to deferred or asynchronous.
  1212. *
  1213. * @param[in] type
  1214. * The new cancellation type for the calling thread. Possible values:
  1215. * - `PTHREAD_CANCEL_DEFERRED`: Cancellation occurs at cancellation points (default behavior).
  1216. * - `PTHREAD_CANCEL_ASYNCHRONOUS`: Cancellation occurs immediately when a request is received.
  1217. *
  1218. * @param[out] oldtype
  1219. * A pointer to an integer where the previous cancellation type will be stored. Can be `NULL`
  1220. * if the previous type is not required.
  1221. *
  1222. * @return
  1223. * - `0` on success.
  1224. * - `EINVAL` if the `type` is not a valid cancellation type.
  1225. *
  1226. * @note
  1227. * - The cancellation type determines when a thread processes a cancellation request:
  1228. * - **Deferred**: The thread responds to cancellation only at well-defined cancellation points.
  1229. * - **Asynchronous**: The thread can be canceled immediately, which may lead to resource inconsistencies.
  1230. * - By default, threads use `PTHREAD_CANCEL_DEFERRED`.
  1231. * - Asynchronous cancellation should be used cautiously as it can interrupt a thread at any point.
  1232. *
  1233. * @see pthread_cancel, pthread_setcancelstate, pthread_testcancel
  1234. */
  1235. int pthread_setcanceltype(int type, int *oldtype)
  1236. {
  1237. _pthread_data_t *ptd;
  1238. if (rt_thread_self() == NULL) return EINVAL;
  1239. /* get pthread data from pthread_data of thread */
  1240. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  1241. RT_ASSERT(ptd != RT_NULL);
  1242. if ((type != PTHREAD_CANCEL_DEFERRED) && (type != PTHREAD_CANCEL_ASYNCHRONOUS))
  1243. return EINVAL;
  1244. if (oldtype)
  1245. *oldtype = ptd->canceltype;
  1246. ptd->canceltype = type;
  1247. return 0;
  1248. }
  1249. RTM_EXPORT(pthread_setcanceltype);
  1250. /**
  1251. * @brief Explicitly checks for pending cancellation requests in the calling thread.
  1252. *
  1253. * The `pthread_testcancel` function allows a thread to determine if it has a pending
  1254. * cancellation request. If a cancellation request is pending and the thread's cancelability
  1255. * state is set to `PTHREAD_CANCEL_ENABLE`, the thread will terminate immediately.
  1256. *
  1257. * @note
  1258. * - This function is a cancellation point, meaning it checks for cancellation and responds if applicable.
  1259. * - If the thread's cancelability state is `PTHREAD_CANCEL_DISABLE`, the function has no effect.
  1260. * - The thread will invoke any cleanup handlers registered with `pthread_cleanup_push` before termination.
  1261. *
  1262. * @return
  1263. * This function does not return if a cancellation is performed. Otherwise, it returns normally.
  1264. *
  1265. * @see pthread_setcancelstate, pthread_setcanceltype, pthread_cancel
  1266. */
  1267. void pthread_testcancel(void)
  1268. {
  1269. int cancel = 0;
  1270. _pthread_data_t *ptd;
  1271. if (rt_thread_self() == NULL) return;
  1272. /* get pthread data from pthread_data of thread */
  1273. ptd = (_pthread_data_t *)rt_thread_self()->pthread_data;
  1274. RT_ASSERT(ptd != RT_NULL);
  1275. if (ptd->cancelstate == PTHREAD_CANCEL_ENABLE)
  1276. cancel = ptd->canceled;
  1277. if (cancel)
  1278. pthread_exit((void *)PTHREAD_CANCELED);
  1279. }
  1280. RTM_EXPORT(pthread_testcancel);
  1281. /**
  1282. * @brief Sends a cancellation request to a specified thread.
  1283. *
  1284. * The `pthread_cancel` function requests the cancellation of the thread identified by `thread`.
  1285. * The actual response to the request depends on the target thread's cancelability state and type.
  1286. *
  1287. * @param[in] thread
  1288. * The identifier of the thread to be canceled.
  1289. *
  1290. * @return
  1291. * - `0` on success.
  1292. * - `EINVAL` if the specified thread does not exist.
  1293. *
  1294. * @note
  1295. * - Cancellation is an asynchronous mechanism. The thread may not terminate immediately or at all
  1296. * if its cancelability state is set to `PTHREAD_CANCEL_DISABLE`.
  1297. * - If the thread is cancelable and terminates, it invokes cleanup handlers registered with
  1298. * `pthread_cleanup_push` before termination.
  1299. * - The thread's cancellation type determines when it processes the cancellation request:
  1300. * - `PTHREAD_CANCEL_DEFERRED` (default): At specific cancellation points.
  1301. * - `PTHREAD_CANCEL_ASYNCHRONOUS`: Immediately upon receipt of the request.
  1302. *
  1303. * @see pthread_setcancelstate, pthread_setcanceltype, pthread_testcancel
  1304. */
  1305. int pthread_cancel(pthread_t thread)
  1306. {
  1307. _pthread_data_t *ptd;
  1308. _pthread_cleanup_t *cleanup;
  1309. rt_thread_t tid;
  1310. /* get posix thread data */
  1311. ptd = _pthread_get_data(thread);
  1312. if (ptd == RT_NULL)
  1313. {
  1314. return EINVAL;
  1315. }
  1316. tid = ptd->tid;
  1317. /* cancel self */
  1318. if (ptd->tid == rt_thread_self())
  1319. return 0;
  1320. /* set canceled */
  1321. if (ptd->cancelstate == PTHREAD_CANCEL_ENABLE)
  1322. {
  1323. ptd->canceled = 1;
  1324. if (ptd->canceltype == PTHREAD_CANCEL_ASYNCHRONOUS)
  1325. {
  1326. /*
  1327. * When use pthread_cancel to exit.
  1328. * invoke pushed cleanup
  1329. */
  1330. while (ptd->cleanup != RT_NULL)
  1331. {
  1332. cleanup = ptd->cleanup;
  1333. ptd->cleanup = cleanup->next;
  1334. cleanup->cleanup_func(cleanup->parameter);
  1335. /* release this cleanup function */
  1336. rt_free(cleanup);
  1337. }
  1338. /* According to "detachstate" to whether or not to recycle resource immediately */
  1339. if (ptd->attr.detachstate == PTHREAD_CREATE_JOINABLE)
  1340. {
  1341. /* set value */
  1342. rt_sem_release(ptd->joinable_sem);
  1343. }
  1344. else
  1345. {
  1346. /* release pthread resource */
  1347. _pthread_data_destroy(ptd);
  1348. }
  1349. /*
  1350. * second: detach thread.
  1351. * this thread will be removed from scheduler list
  1352. * and because there is a cleanup function in the
  1353. * thread (pthread_cleanup), it will move to defunct
  1354. * thread list and wait for handling in idle thread.
  1355. */
  1356. rt_thread_detach(tid);
  1357. }
  1358. }
  1359. return 0;
  1360. }
  1361. RTM_EXPORT(pthread_cancel);