mutex.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2015 Kaspar Schleiser <kaspar@schleiser.de>
3  * 2013, 2014 Freie Universität Berlin
4  *
5  * This file is subject to the terms and conditions of the GNU Lesser
6  * General Public License v2.1. See the file LICENSE in the top level
7  * directory for more details.
8  */
9 
102 #ifndef MUTEX_H
103 #define MUTEX_H
104 
105 #include <stddef.h>
106 #include <stdint.h>
107 
108 #include "irq.h"
109 #include "kernel_defines.h"
110 #include "list.h"
111 #include "thread.h"
112 
113 #ifdef __cplusplus
114 extern "C" {
115 #endif
116 
120 typedef struct {
127 } mutex_t;
128 
133 #define MUTEX_INIT { { NULL } }
134 
138 #define MUTEX_INIT_LOCKED { { MUTEX_LOCKED } }
139 
145 #define MUTEX_LOCKED ((list_node_t *)-1)
146 
156 static inline void mutex_init(mutex_t *mutex)
157 {
158  mutex->queue.next = NULL;
159 }
160 
173 static inline int mutex_trylock(mutex_t *mutex)
174 {
175  unsigned irq_state = irq_disable();
176  int retval = 0;
177  if (mutex->queue.next == NULL) {
178  mutex->queue.next = MUTEX_LOCKED;
179  retval = 1;
180  };
181  irq_restore(irq_state);
182  return retval;
183 }
184 
196 void mutex_lock(mutex_t *mutex);
197 
207 void mutex_unlock(mutex_t *mutex);
208 
216 void mutex_unlock_and_sleep(mutex_t *mutex);
217 
218 #ifdef __cplusplus
219 }
220 #endif
221 
222 #endif /* MUTEX_H */
223 
mutex_lock
void mutex_lock(mutex_t *mutex)
Locks a mutex, blocking.
kernel_defines.h
Common macros and compiler attributes/pragmas configuration.
irq_disable
MAYBE_INLINE unsigned irq_disable(void)
This function sets the IRQ disable bit in the status register.
mutex_t::queue
list_node_t queue
The process waiting queue of the mutex.
Definition: mutex.h:126
irq_restore
MAYBE_INLINE void irq_restore(unsigned state)
This function restores the IRQ disable bit in the status register to the value contained within passe...
mutex_trylock
static int mutex_trylock(mutex_t *mutex)
Tries to get a mutex, non-blocking.
Definition: mutex.h:173
mutex_init
static void mutex_init(mutex_t *mutex)
Initializes a mutex object.
Definition: mutex.h:156
mutex_unlock_and_sleep
void mutex_unlock_and_sleep(mutex_t *mutex)
Unlocks the mutex and sends the current thread to sleep.
thread.h
Threading API.
irq.h
IRQ driver interface.
list_node
List node structure.
Definition: list.h:40
list_node::next
struct list_node * next
pointer to next list entry
Definition: list.h:41
list.h
Intrusive linked list.
mutex_unlock
void mutex_unlock(mutex_t *mutex)
Unlocks the mutex.
mutex_t
Mutex structure.
Definition: mutex.h:120