-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathG8RTOS_Semaphores.c
84 lines (65 loc) · 2.32 KB
/
G8RTOS_Semaphores.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* G8RTOS_Semaphores.c
*/
/*********************************************** Dependencies and Externs *************************************************************/
#include <stdint.h>
#include "msp.h"
#include <G8RTOS/G8RTOS_Semaphores.h>
#include <G8RTOS/G8RTOS_CriticalSection.h>
#include <G8RTOS/G8RTOS_Scheduler.h>
#include <G8RTOS/G8RTOS_Structures.h>
/*********************************************** Dependencies and Externs *************************************************************/
/*********************************************** Public Functions *********************************************************************/
/*
* Initializes a semaphore to a given value
* Param "s": Pointer to semaphore
* Param "value": Value to initialize semaphore to
* THIS IS A CRITICAL SECTION
*/
void G8RTOS_InitSemaphore(semaphore_t *s, int32_t value)
{
uint32_t savedmask = StartCriticalSection(); // disable interrupts (end critical section)
*s=value;
EndCriticalSection(savedmask); // enable interrupts
}
/*
* Waits for a semaphore to be available (value greater than 0)
* - Decrements semaphore when available
* - Spinlocks to wait for semaphore
* Param "s": Pointer to semaphore to wait on
* THIS IS A CRITICAL SECTION
*/
void G8RTOS_AcquireSemaphore(semaphore_t *s)
{
uint32_t savedmask = StartCriticalSection(); // disable interrupts
(*s)--;
if ((*s) < 0)
{
CurrentlyRunningThread->blocked = s;
EndCriticalSection(savedmask); // enable interrupts
G8RTOS_Yield(); // triggers context switch to let other thread go instead
}
EndCriticalSection(savedmask);
}
/*
* Signals the completion of the usage of a semaphore
* - Increments the semaphore value by 1
* Param "s": Pointer to semaphore to be signalled
* THIS IS A CRITICAL SECTION
*/
void G8RTOS_ReleaseSemaphore(semaphore_t *s)
{
uint32_t savedmask = StartCriticalSection();
(*s)++; // set the semaphore - resource
if ((*s) <= 0)
{
tcb_t *pt = CurrentlyRunningThread->next;
while(pt->blocked != s)
{
pt = pt->next;
}
pt->blocked = 0;
}
EndCriticalSection(savedmask);
}
/*********************************************** Public Functions *********************************************************************/