aboutsummaryrefslogtreecommitdiffstats
path: root/extras/mini-os/include/semaphore.h
blob: d30c81e674f484a3bb8177e26a61363b86b4a390 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#ifndef _SEMAPHORE_H_
#define _SEMAPHORE_H_

#include <wait.h>

/*
 * Implementation of semaphore in Mini-os is simple, because 
 * there are no preemptive threads, the atomicity is guaranteed.
 */

struct semaphore
{
	int count;
	struct wait_queue_head wait;
};


#define __SEMAPHORE_INITIALIZER(name, n)                            \
{                                                                   \
    .count    = n,                                                  \
    .wait           = __WAIT_QUEUE_HEAD_INITIALIZER((name).wait)    \
}

#define __MUTEX_INITIALIZER(name) \
    __SEMAPHORE_INITIALIZER(name,1)
                           
#define __DECLARE_SEMAPHORE_GENERIC(name,count) \
    struct semaphore name = __SEMAPHORE_INITIALIZER(name,count)
    
#define DECLARE_MUTEX(name) __DECLARE_SEMAPHORE_GENERIC(name,1)

#define DECLARE_MUTEX_LOCKED(name) __DECLARE_SEMAPHORE_GENERIC(name,0)

static void inline down(struct semaphore *sem)
{
    wait_event(sem->wait, sem->count > 0);
    sem->count--;
}

static void inline up(struct semaphore *sem)
{
    sem->count++;
    wake_up(&sem->wait);
}

#endif /* _SEMAPHORE_H */