summaryrefslogtreecommitdiff
path: root/user/libthread/sem.c
blob: d4d723e45bdfc6ac6d8822757fd1e971c85ca534 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
 * @file sem.c
 * @author Hanjie Wu (hanjiew)
 * @author Devang Acharya (devanga)
 * @brief Semaphore implementation
 * @date 2023-02-22
 * 
 */


#include <sem.h>

/**
 * @brief Initializes the semaphore pointed to by 'sem' tp value 'count'
 *
 * @param sem semaphore
 * @param count count
 * @return int
 */
int sem_init(sem_t* sem, int count) {
    sem->value = count;

    mutex_init(&sem->value_lock);
    cond_init(&sem->value_cv);

    return 0;
}

/**
 * @brief Decrement sem value, may block until it is possible to do so
 *
 * @param sem semaphore
 */
void sem_wait(sem_t* sem) {
    mutex_lock(&sem->value_lock);

    while (sem->value <= 0) {
        /* wait until value goes up */
        cond_wait(&sem->value_cv, &sem->value_lock);
    }
    sem->value -= 1;
    mutex_unlock(&sem->value_lock);
}

/**
 * @brief  wake up a thread waiting on the semaphore pointed to by sem
 *
 * @param sem semaphore
 */
void sem_signal(sem_t* sem) {
    mutex_lock(&sem->value_lock);

    sem->value += 1;

    if (sem->value == 1) {
        /* notify when value goes up from zero */
        cond_signal(&sem->value_cv);
    }
    mutex_unlock(&sem->value_lock);
}

/**
 * @brief deactivate semaphore. Must not be called on semaphores bwing waited
 *        upon
 *
 * @param sem semaphore
 */
void sem_destroy(sem_t* sem) {
    mutex_destroy(&sem->value_lock);
    cond_destroy(&sem->value_cv);
}