1 /***************************************************************************
2 * Copyright (c) 2024 Microsoft Corporation
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the MIT License which is available at
6 * https://opensource.org/licenses/MIT.
7 *
8 * SPDX-License-Identifier: MIT
9 **************************************************************************/
10
11
12 /**************************************************************************/
13 /**************************************************************************/
14 /** */
15 /** POSIX wrapper for THREADX */
16 /** */
17 /** */
18 /** */
19 /**************************************************************************/
20 /**************************************************************************/
21
22 /* Include necessary system files. */
23
24 #include "tx_api.h" /* Threadx API */
25 #include "pthread.h" /* Posix API */
26 #include "px_int.h" /* Posix helper functions */
27
28
29 /**************************************************************************/
30 /* */
31 /* FUNCTION RELEASE */
32 /* */
33 /* sem_wait PORTABLE C */
34 /* 6.1.7 */
35 /* AUTHOR */
36 /* */
37 /* William E. Lamie, Microsoft Corporation */
38 /* */
39 /* DESCRIPTION */
40 /* */
41 /* This function locks (takes) a semaphore. */
42 /* */
43 /* INPUT */
44 /* */
45 /* *sem Pointer to Semaphore */
46 /* */
47 /* OUTPUT */
48 /* */
49 /* OK If successful */
50 /* ERROR If error occurs */
51 /* */
52 /* CALLS */
53 /* */
54 /* tx_thread_identify To check whether calling from a thread */
55 /* tx_semaphore_get ThreadX Semaphore get */
56 /* posix_internal_error Returns a generic error */
57 /* */
58 /* CALLED BY */
59 /* */
60 /* Application Code */
61 /* */
62 /* RELEASE HISTORY */
63 /* */
64 /* DATE NAME DESCRIPTION */
65 /* */
66 /* 06-02-2021 William E. Lamie Initial Version 6.1.7 */
67 /* */
68 /**************************************************************************/
sem_wait(sem_t * sem)69 INT sem_wait( sem_t * sem )
70 {
71
72 TX_SEMAPHORE * TheSem;
73
74
75 /* Make sure we're calling this routine from a thread context. */
76 if (! tx_thread_identify())
77 {
78 /* No wait when called from ISR. */
79 posix_internal_error(242);
80
81 /* Return Error. */
82 return (ERROR);
83 }
84
85 /* get ThreadX semaphore. */
86 TheSem = (TX_SEMAPHORE *)sem;
87
88 /* Check for an invalid semaphore pointer. */
89 if ((!TheSem) || (TheSem -> tx_semaphore_id != TX_SEMAPHORE_ID))
90 {
91 /* error in POSIX. */
92 posix_errno = EINVAL;
93 posix_set_pthread_errno(EINVAL);
94
95 /* Return error. */
96 return (EINVAL);
97 }
98 else
99 {
100 /* Takes the semaphore. */
101 if(tx_semaphore_get(TheSem,TX_WAIT_FOREVER))
102 {
103 /* Return general error. */
104 posix_internal_error(246);
105
106 /* Return error. */
107 return(ERROR);
108 }
109
110 return (OK);
111 }
112 }
113