1 | /** |
---|
2 | * @file |
---|
3 | * |
---|
4 | * @brief Lock a Semaphore |
---|
5 | * @ingroup POSIX_SEMAPHORE POSIX Semaphores Support |
---|
6 | */ |
---|
7 | |
---|
8 | /* |
---|
9 | * COPYRIGHT (c) 1989-2008. |
---|
10 | * On-Line Applications Research Corporation (OAR). |
---|
11 | * |
---|
12 | * The license and distribution terms for this file may be |
---|
13 | * found in the file LICENSE in this distribution or at |
---|
14 | * http://www.rtems.org/license/LICENSE. |
---|
15 | */ |
---|
16 | |
---|
17 | #if HAVE_CONFIG_H |
---|
18 | #include "config.h" |
---|
19 | #endif |
---|
20 | |
---|
21 | #include <rtems/posix/semaphoreimpl.h> |
---|
22 | #include <rtems/score/todimpl.h> |
---|
23 | |
---|
24 | /* |
---|
25 | * 11.2.6 Lock a Semaphore, P1003.1b-1993, p.226 |
---|
26 | * |
---|
27 | * NOTE: P1003.4b/D8 adds sem_timedwait(), p. 27 |
---|
28 | */ |
---|
29 | |
---|
30 | int sem_timedwait( |
---|
31 | sem_t *__restrict _sem, |
---|
32 | const struct timespec *__restrict abstime |
---|
33 | ) |
---|
34 | { |
---|
35 | Sem_Control *sem; |
---|
36 | Thread_queue_Context queue_context; |
---|
37 | ISR_Level level; |
---|
38 | Thread_Control *executing; |
---|
39 | unsigned int count; |
---|
40 | |
---|
41 | POSIX_SEMAPHORE_VALIDATE_OBJECT( _sem ); |
---|
42 | |
---|
43 | sem = _Sem_Get( &_sem->_Semaphore ); |
---|
44 | _Thread_queue_Context_initialize( &queue_context ); |
---|
45 | _Thread_queue_Context_ISR_disable( &queue_context, level ); |
---|
46 | executing = _Sem_Queue_acquire_critical( sem, &queue_context ); |
---|
47 | |
---|
48 | count = sem->count; |
---|
49 | if ( __predict_true( count > 0 ) ) { |
---|
50 | sem->count = count - 1; |
---|
51 | _Sem_Queue_release( sem, level, &queue_context ); |
---|
52 | return 0; |
---|
53 | } else { |
---|
54 | Status_Control status; |
---|
55 | |
---|
56 | _Thread_queue_Context_set_thread_state( |
---|
57 | &queue_context, |
---|
58 | STATES_WAITING_FOR_SEMAPHORE |
---|
59 | ); |
---|
60 | _Thread_queue_Context_set_enqueue_timeout_realtime_timespec( |
---|
61 | &queue_context, |
---|
62 | abstime |
---|
63 | ); |
---|
64 | _Thread_queue_Context_set_ISR_level( &queue_context, level ); |
---|
65 | _Thread_queue_Enqueue( |
---|
66 | &sem->Queue.Queue, |
---|
67 | SEMAPHORE_TQ_OPERATIONS, |
---|
68 | executing, |
---|
69 | &queue_context |
---|
70 | ); |
---|
71 | status = _Thread_Wait_get_status( executing ); |
---|
72 | return _POSIX_Zero_or_minus_one_plus_errno( status ); |
---|
73 | } |
---|
74 | } |
---|