pthread_cond.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. * 2010-10-26 Bernard the first version
  9. * 2022-06-27 xiangxistu use atomic operation to protect pthread conditional variable
  10. */
  11. #include <rthw.h>
  12. #include <pthread.h>
  13. #include "pthread_internal.h"
  14. int pthread_condattr_destroy(pthread_condattr_t *attr)
  15. {
  16. if (!attr)
  17. return EINVAL;
  18. return 0;
  19. }
  20. RTM_EXPORT(pthread_condattr_destroy);
  21. int pthread_condattr_init(pthread_condattr_t *attr)
  22. {
  23. if (!attr)
  24. return EINVAL;
  25. *attr = PTHREAD_PROCESS_PRIVATE;
  26. return 0;
  27. }
  28. RTM_EXPORT(pthread_condattr_init);
  29. int pthread_condattr_getclock(const pthread_condattr_t *attr,
  30. clockid_t *clock_id)
  31. {
  32. return 0;
  33. }
  34. RTM_EXPORT(pthread_condattr_getclock);
  35. int pthread_condattr_setclock(pthread_condattr_t *attr,
  36. clockid_t clock_id)
  37. {
  38. return 0;
  39. }
  40. RTM_EXPORT(pthread_condattr_setclock);
  41. int pthread_condattr_getpshared(const pthread_condattr_t *attr, int *pshared)
  42. {
  43. if (!attr || !pshared)
  44. return EINVAL;
  45. *pshared = PTHREAD_PROCESS_PRIVATE;
  46. return 0;
  47. }
  48. RTM_EXPORT(pthread_condattr_getpshared);
  49. int pthread_condattr_setpshared(pthread_condattr_t *attr, int pshared)
  50. {
  51. if ((pshared != PTHREAD_PROCESS_PRIVATE) &&
  52. (pshared != PTHREAD_PROCESS_SHARED))
  53. {
  54. return EINVAL;
  55. }
  56. if (pshared != PTHREAD_PROCESS_PRIVATE)
  57. return ENOSYS;
  58. return 0;
  59. }
  60. RTM_EXPORT(pthread_condattr_setpshared);
  61. /**
  62. * @brief Initializes a condition variable.
  63. *
  64. * This function initializes the condition variable pointed to by `cond` with the attributes
  65. * specified by `attr`. If `attr` is NULL, the condition variable is initialized with the
  66. * default attributes.
  67. *
  68. * @param cond A pointer to the condition variable to be initialized.
  69. * Must point to valid memory.
  70. * @param attr A pointer to the condition variable attributes object.
  71. * If NULL, default attributes are used.
  72. *
  73. * @return
  74. * - `0` on success.
  75. * - A non-zero error code on failure, including:
  76. * - `EINVAL`: Invalid attributes, invalid condition variable pointer, or semaphore init failed.
  77. *
  78. * @note
  79. * - The condition variable must not be used until it has been initialized.
  80. * - Each condition variable must be destroyed using `pthread_cond_destroy()`
  81. * once it is no longer needed.
  82. *
  83. * @see pthread_cond_destroy, pthread_cond_wait, pthread_cond_signal, pthread_cond_broadcast
  84. */
  85. int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
  86. {
  87. rt_err_t result;
  88. char cond_name[RT_NAME_MAX];
  89. static rt_uint16_t cond_num = 0;
  90. /* parameter check */
  91. if (cond == RT_NULL)
  92. return EINVAL;
  93. if ((attr != RT_NULL) && (*attr != PTHREAD_PROCESS_PRIVATE))
  94. return EINVAL;
  95. rt_snprintf(cond_name, sizeof(cond_name), "cond%02d", cond_num++);
  96. /* use default value */
  97. if (attr == RT_NULL)
  98. {
  99. cond->attr = PTHREAD_PROCESS_PRIVATE;
  100. }
  101. else
  102. {
  103. cond->attr = *attr;
  104. }
  105. result = rt_sem_init(&cond->sem, cond_name, 0, RT_IPC_FLAG_FIFO);
  106. if (result != RT_EOK)
  107. {
  108. return EINVAL;
  109. }
  110. /* detach the object from system object container */
  111. rt_object_detach(&(cond->sem.parent.parent));
  112. cond->sem.parent.parent.type = RT_Object_Class_Semaphore;
  113. return 0;
  114. }
  115. RTM_EXPORT(pthread_cond_init);
  116. /**
  117. * @brief Destroys a condition variable.
  118. *
  119. * This function destroys the condition variable pointed to by `cond`. After a condition
  120. * variable is destroyed, it must not be used until it is reinitialized with
  121. * `pthread_cond_init`.
  122. *
  123. * @param cond A pointer to the condition variable to be destroyed.
  124. * Must point to a valid, previously initialized condition variable.
  125. *
  126. * @return
  127. * - `0` on success.
  128. * - A non-zero error code on failure, including:
  129. * - `EBUSY`: The condition variable is currently in use by other threads.
  130. * - `EINVAL`: The condition variable is invalid or uninitialized.
  131. *
  132. * @note
  133. * - The condition variable must not be destroyed while it is being used by other threads
  134. * (e.g., in `pthread_cond_wait` or `pthread_cond_timedwait`).
  135. * - Attempting to destroy a condition variable that has not been initialized results in
  136. * undefined behavior.
  137. *
  138. * @see pthread_cond_init, pthread_cond_wait, pthread_cond_signal, pthread_cond_broadcast
  139. */
  140. int pthread_cond_destroy(pthread_cond_t *cond)
  141. {
  142. rt_err_t result;
  143. if (cond == RT_NULL)
  144. {
  145. return EINVAL;
  146. }
  147. /* which is not initialized */
  148. if (cond->attr == -1)
  149. {
  150. return 0;
  151. }
  152. if (!rt_list_isempty(&cond->sem.parent.suspend_thread))
  153. {
  154. return EBUSY;
  155. }
  156. __retry:
  157. result = rt_sem_trytake(&(cond->sem));
  158. if (result == EBUSY)
  159. {
  160. pthread_cond_broadcast(cond);
  161. goto __retry;
  162. }
  163. /* clean condition */
  164. rt_memset(cond, 0, sizeof(pthread_cond_t));
  165. cond->attr = -1;
  166. return 0;
  167. }
  168. RTM_EXPORT(pthread_cond_destroy);
  169. /**
  170. * @brief Unblocks all threads waiting on the specified condition variable.
  171. *
  172. * This function wakes up all threads that are currently blocked on the condition variable
  173. * pointed to by `cond`. The condition variable must be associated with a mutex, and
  174. * threads waiting on the condition variable should recheck the condition after being
  175. * unblocked.
  176. *
  177. * @param cond A pointer to the condition variable.
  178. * Must point to a valid, initialized condition variable.
  179. *
  180. * @return
  181. * - `0` on success.
  182. * - A non-zero error code on failure, including:
  183. * - `EINVAL`: The condition variable is invalid or uninitialized.
  184. *
  185. * @note
  186. * - Calling this function does not release the associated mutex.
  187. * - Waking up threads does not guarantee that any specific thread will acquire the
  188. * mutex immediately, as thread scheduling depends on the system.
  189. * - Typically used when the condition might allow multiple waiting threads to proceed.
  190. *
  191. * @see pthread_cond_signal, pthread_cond_wait, pthread_cond_init, pthread_cond_destroy
  192. */
  193. int pthread_cond_broadcast(pthread_cond_t *cond)
  194. {
  195. rt_err_t result;
  196. if (cond == RT_NULL)
  197. return EINVAL;
  198. if (cond->attr == -1)
  199. pthread_cond_init(cond, RT_NULL);
  200. while (1)
  201. {
  202. /* try to take condition semaphore */
  203. result = rt_sem_trytake(&(cond->sem));
  204. if (result == -RT_ETIMEOUT)
  205. {
  206. /* it's timeout, release this semaphore */
  207. rt_sem_release(&(cond->sem));
  208. }
  209. else if (result == RT_EOK)
  210. {
  211. /* has taken this semaphore, release it */
  212. rt_sem_release(&(cond->sem));
  213. break;
  214. }
  215. else
  216. {
  217. return EINVAL;
  218. }
  219. }
  220. return 0;
  221. }
  222. RTM_EXPORT(pthread_cond_broadcast);
  223. /**
  224. * @brief Wakes up one thread waiting on the specified condition variable.
  225. *
  226. * This function unblocks one thread that is currently waiting on the
  227. * condition variable `cond`. If multiple threads are waiting, the thread to wake
  228. * up is determined by the system's scheduling policies.
  229. *
  230. * @param cond A pointer to the condition variable to signal.
  231. * Must point to a valid and initialized condition variable.
  232. *
  233. * @return
  234. * - `0` on success.
  235. * - A non-zero error code on failure, including:
  236. * - `EINVAL`: The condition variable is invalid or uninitialized.
  237. *
  238. * @note
  239. * - This function does not release the associated mutex.
  240. * - If no threads are currently waiting on the condition variable, the call has no effect.
  241. * - The awakened thread will not run until it can reacquire the associated mutex and
  242. * re-evaluate the waiting condition.
  243. * - It is typically used when only one waiting thread should be allowed to proceed.
  244. *
  245. * @see pthread_cond_broadcast, pthread_cond_wait, pthread_cond_init, pthread_cond_destroy
  246. */
  247. int pthread_cond_signal(pthread_cond_t *cond)
  248. {
  249. rt_base_t temp;
  250. rt_err_t result;
  251. if (cond == RT_NULL)
  252. return EINVAL;
  253. if (cond->attr == -1)
  254. pthread_cond_init(cond, RT_NULL);
  255. /* disable interrupt */
  256. temp = rt_hw_interrupt_disable();
  257. if (rt_list_isempty(&cond->sem.parent.suspend_thread))
  258. {
  259. /* enable interrupt */
  260. rt_hw_interrupt_enable(temp);
  261. return 0;
  262. }
  263. else
  264. {
  265. /* enable interrupt */
  266. rt_hw_interrupt_enable(temp);
  267. result = rt_sem_release(&(cond->sem));
  268. if (result == RT_EOK)
  269. {
  270. return 0;
  271. }
  272. return 0;
  273. }
  274. }
  275. RTM_EXPORT(pthread_cond_signal);
  276. /**
  277. * @brief Waits on a condition variable with a timeout.
  278. *
  279. * This function causes the calling thread to block on the condition variable `cond`,
  280. * releasing the associated mutex `mutex`. The thread will remain blocked until
  281. * one of the following occurs:
  282. * - It is signaled or broadcast using `pthread_cond_signal` or `pthread_cond_broadcast`.
  283. * - The specified timeout expires.
  284. *
  285. * @param cond A pointer to the condition variable to wait on.
  286. * Must point to a valid, initialized condition variable.
  287. * @param mutex A pointer to the mutex associated with the condition variable.
  288. * Must be locked by the calling thread before invoking this function.
  289. * @param timeout The timeout duration in milliseconds. A value of `RT_WAITING_FOREVER`
  290. * indicates the thread will wait indefinitely.
  291. *
  292. * @return
  293. * - `RT_EOK` on successful wakeup (signaled or broadcast).
  294. * - `-RT_ETIMEOUT` if the timeout expires before the condition variable is signaled.
  295. * - `-RT_ERROR` if an error occurs (e.g., invalid parameters).
  296. *
  297. * @note
  298. * - The mutex is automatically released while the thread waits and re-acquired before
  299. * the function returns.
  300. * - If `timeout` is 0, the function behaves as a non-blocking check.
  301. * - Ensure the condition variable and mutex are properly initialized before use.
  302. *
  303. * @see pthread_cond_signal, pthread_cond_broadcast, pthread_mutex_lock, pthread_mutex_unlock
  304. */
  305. rt_err_t _pthread_cond_timedwait(pthread_cond_t *cond,
  306. pthread_mutex_t *mutex,
  307. rt_int32_t timeout)
  308. {
  309. rt_err_t result = RT_EOK;
  310. rt_sem_t sem;
  311. rt_int32_t time;
  312. sem = &(cond->sem);
  313. if (sem == RT_NULL)
  314. {
  315. return -RT_ERROR;
  316. }
  317. time = timeout;
  318. if (!cond || !mutex)
  319. {
  320. return -RT_ERROR;
  321. }
  322. /* check whether initialized */
  323. if (cond->attr == -1)
  324. {
  325. pthread_cond_init(cond, RT_NULL);
  326. }
  327. /* The mutex was not owned by the current thread at the time of the call. */
  328. if (mutex->lock.owner != rt_thread_self())
  329. {
  330. return -RT_ERROR;
  331. }
  332. {
  333. register rt_base_t temp;
  334. struct rt_thread *thread;
  335. /* parameter check */
  336. RT_ASSERT(sem != RT_NULL);
  337. RT_ASSERT(rt_object_get_type(&sem->parent.parent) == RT_Object_Class_Semaphore);
  338. /* disable interrupt */
  339. temp = rt_hw_interrupt_disable();
  340. if (sem->value > 0)
  341. {
  342. /* semaphore is available */
  343. sem->value--;
  344. /* enable interrupt */
  345. rt_hw_interrupt_enable(temp);
  346. }
  347. else
  348. {
  349. /* no waiting, return with timeout */
  350. if (time == 0)
  351. {
  352. rt_hw_interrupt_enable(temp);
  353. return -RT_ETIMEOUT;
  354. }
  355. else
  356. {
  357. /* current context checking */
  358. RT_DEBUG_IN_THREAD_CONTEXT;
  359. /* semaphore is unavailable, push to suspend list */
  360. /* get current thread */
  361. thread = rt_thread_self();
  362. /* reset thread error number */
  363. thread->error = RT_EOK;
  364. /* suspend thread */
  365. rt_thread_suspend(thread);
  366. /* Only support FIFO */
  367. rt_list_insert_before(&(sem->parent.suspend_thread), &RT_THREAD_LIST_NODE(thread));
  368. /**
  369. rt_ipc_list_suspend(&(sem->parent.suspend_thread),
  370. thread,
  371. sem->parent.parent.flag);
  372. */
  373. /* has waiting time, start thread timer */
  374. if (time > 0)
  375. {
  376. /* reset the timeout of thread timer and start it */
  377. rt_timer_control(&(thread->thread_timer),
  378. RT_TIMER_CTRL_SET_TIME,
  379. &time);
  380. rt_timer_start(&(thread->thread_timer));
  381. }
  382. /* to avoid the lost of singal< cond->sem > */
  383. if (pthread_mutex_unlock(mutex) != 0)
  384. {
  385. return -RT_ERROR;
  386. }
  387. /* enable interrupt */
  388. rt_hw_interrupt_enable(temp);
  389. /* do schedule */
  390. rt_schedule();
  391. result = thread->error;
  392. /* lock mutex again */
  393. pthread_mutex_lock(mutex);
  394. }
  395. }
  396. }
  397. return result;
  398. }
  399. RTM_EXPORT(_pthread_cond_timedwait);
  400. /**
  401. * @brief Waits on a condition variable.
  402. *
  403. * This function blocks the calling thread on the condition variable `cond` and releases
  404. * the associated mutex `mutex`. The thread remains blocked until it is signaled or
  405. * broadcast using `pthread_cond_signal` or `pthread_cond_broadcast`. When the thread
  406. * is awakened, it re-acquires the mutex and resumes execution.
  407. *
  408. * @param cond A pointer to the condition variable to wait on.
  409. * Must point to a valid, initialized condition variable.
  410. * @param mutex A pointer to the mutex associated with the condition variable.
  411. * Must be locked by the calling thread before invoking this function.
  412. *
  413. * @return
  414. * - `0` on success.
  415. * - A non-zero error code on failure, including:
  416. * - `EINVAL`: The condition variable or mutex is invalid or uninitialized.
  417. *
  418. * @note
  419. * - The mutex must be locked before calling this function.
  420. * - Upon returning, the mutex is locked again by the calling thread.
  421. * - Spurious wakeups may occur, so the thread should always recheck the waiting
  422. * condition upon wakeup.
  423. * - This function may block indefinitely unless the condition is signaled or broadcast.
  424. *
  425. * @see pthread_cond_signal, pthread_cond_broadcast, pthread_cond_timedwait, pthread_mutex_lock
  426. */
  427. int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
  428. {
  429. rt_err_t result;
  430. __retry:
  431. result = _pthread_cond_timedwait(cond, mutex, RT_WAITING_FOREVER);
  432. if (result == RT_EOK)
  433. {
  434. return 0;
  435. }
  436. else if (result == -RT_EINTR)
  437. {
  438. /* https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_wait.html
  439. * These functions shall not return an error code of [EINTR].
  440. */
  441. goto __retry;
  442. }
  443. return EINVAL;
  444. }
  445. RTM_EXPORT(pthread_cond_wait);
  446. /**
  447. * @brief Waits on a condition variable with a timeout.
  448. *
  449. * This function blocks the calling thread on the condition variable `cond`, releasing
  450. * the associated mutex `mutex`. The thread remains blocked until one of the following occurs:
  451. * - The condition variable is signaled or broadcast using `pthread_cond_signal` or `pthread_cond_broadcast`.
  452. * - The specified absolute timeout `abstime` is reached.
  453. * - A spurious wakeup occurs (requiring the thread to recheck the condition).
  454. *
  455. * @param cond A pointer to the condition variable to wait on.
  456. * Must point to a valid, initialized condition variable.
  457. * @param mutex A pointer to the mutex associated with the condition variable.
  458. * Must be locked by the calling thread before invoking this function.
  459. * @param abstime A pointer to a `struct timespec` specifying the absolute timeout (in seconds and nanoseconds
  460. * since the Epoch). If the time specified is already reached, the function immediately returns.
  461. *
  462. * @return
  463. * - `0` on successful wakeup (signaled or broadcast).
  464. * - `ETIMEDOUT` if the timeout expires before the condition variable is signaled.
  465. * - A non-zero error code on failure, including:
  466. * - `EINVAL`: The condition variable, mutex, or `abstime` is invalid.
  467. * - `EPERM`: The mutex is not owned by the calling thread.
  468. *
  469. * @note
  470. * - The mutex is released while the thread is waiting and re-acquired before the function returns.
  471. * - Spurious wakeups may occur, so the thread must always recheck the waiting condition upon wakeup.
  472. * - The timeout is specified in absolute time, not relative duration.
  473. * - Ensure the condition variable and mutex are properly initialized before use.
  474. *
  475. * @see pthread_cond_wait, pthread_cond_signal, pthread_cond_broadcast, pthread_mutex_lock
  476. */
  477. int pthread_cond_timedwait(pthread_cond_t *cond,
  478. pthread_mutex_t *mutex,
  479. const struct timespec *abstime)
  480. {
  481. int timeout;
  482. rt_err_t result;
  483. timeout = rt_timespec_to_tick(abstime);
  484. result = _pthread_cond_timedwait(cond, mutex, timeout);
  485. if (result == RT_EOK)
  486. {
  487. return 0;
  488. }
  489. if (result == -RT_ETIMEOUT)
  490. {
  491. return ETIMEDOUT;
  492. }
  493. return EINVAL;
  494. }
  495. RTM_EXPORT(pthread_cond_timedwait);