pthread.c 45 KB

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