4 * Copyright 2001,2004 Develer S.r.l. (http://www.develer.com/)
5 * Copyright 1999,2000,2001 Bernardo Innocenti <bernie@develer.com>
9 * \brief Semaphore based synchronization services.
13 * \author Bernardo Innocenti <bernie@develer.com>
18 * Revision 1.1 2004/05/23 17:27:00 bernie
19 * Import kern/ subdirectory.
31 * \brief Initialize a Semaphore structure
33 void sem_init(struct Semaphore *s)
35 INITLIST(&s->wait_queue);
42 * \brief Attempt to lock a semaphore without waiting.
44 * \return true in case of success, false if the semaphore
45 * was already locked by someone else.
47 * \note each call to sem_attempt() must be matched by a
48 * call to sem_release().
50 bool sem_attempt(struct Semaphore *s)
53 if ((!s->owner) || (s->owner == CurrentProcess))
55 s->owner = CurrentProcess;
66 * \brief Lock a semaphore.
68 * If the semaphore is already owned by another process, the caller
69 * process will be enqueued into the waiting list and sleep until
70 * the semaphore is available.
72 * \note Each call to sem_obtain() must be matched by a
73 * call to sem_release().
75 * \note This routine is optimized for highest speed in
76 * the most common case: the semaphore is free or locked
77 * by the calling process itself. Rearranging this code
78 * is probably a bad idea.
80 void sem_obtain(struct Semaphore *s)
84 /* Is the semaphore already locked by another process? */
85 if (s->owner && (s->owner != CurrentProcess))
87 /* Append calling process to the wait queue */
88 ADDTAIL(&s->wait_queue, (Node *)CurrentProcess);
91 /* We will awake only when the current owner calls
92 * ReleaseSemaphore(). Then, the semaphore will already
99 /* The semaphore is free: lock it */
100 s->owner = CurrentProcess;
108 * \brief Releases a lock on a previously locked semaphore.
110 * If the nesting count of the semaphore reaches zero,
111 * the next process waiting for it will be awaken.
113 * \note This routine is optimized for highest speed in
114 * the most common case: the semaphore has been locked just
115 * once and nobody else was waiting for it. Rearranging
116 * this code is probably a bad idea.
118 void sem_release(struct Semaphore *s)
122 /* Decremement nesting count and check if the semaphore
123 * has been fully unlocked
125 if (--s->nest_count == 0)
127 /* Disown semaphore */
130 /* Anybody still waiting for this semaphore? */
131 if (!ISLISTEMPTY(&s->wait_queue))
133 /* Give semaphore to the first applicant */
134 Process *proc = (Process *)s->wait_queue.head;
135 REMOVE((Node *)proc);