|
| 1 | +package freertos |
| 2 | + |
| 3 | +// #include <freertos/FreeRTOS.h> |
| 4 | +// #include <freertos/semphr.h> |
| 5 | +import "C" |
| 6 | +import ( |
| 7 | + "sync" |
| 8 | + "unsafe" |
| 9 | + |
| 10 | + "internal/task" |
| 11 | +) |
| 12 | + |
| 13 | +type Semaphore struct { |
| 14 | + lock sync.Mutex // the lock itself |
| 15 | + task *task.Task // the task currently locking this semaphore |
| 16 | + count uint32 // how many times this semaphore is locked |
| 17 | +} |
| 18 | + |
| 19 | +//export xSemaphoreCreateRecursiveMutex |
| 20 | +func xSemaphoreCreateRecursiveMutex() C.SemaphoreHandle_t { |
| 21 | + var mutex Semaphore |
| 22 | + return (C.SemaphoreHandle_t)(unsafe.Pointer(&mutex)) |
| 23 | +} |
| 24 | + |
| 25 | +//export vSemaphoreDelete |
| 26 | +func vSemaphoreDelete(xSemaphore C.SemaphoreHandle_t) { |
| 27 | + mutex := (*Semaphore)(unsafe.Pointer(xSemaphore)) |
| 28 | + if mutex.task != nil { |
| 29 | + panic("vSemaphoreDelete: still locked") |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +//export xSemaphoreTakeRecursive |
| 34 | +func xSemaphoreTakeRecursive(xMutex C.SemaphoreHandle_t, xTicksToWait C.TickType_t) C.BaseType_t { |
| 35 | + println("take recursive") |
| 36 | + // TODO: implement xTickToWait, or at least when xTicksToWait equals 0. |
| 37 | + mutex := (*Semaphore)(unsafe.Pointer(xMutex)) |
| 38 | + if mutex.task == task.Current() { |
| 39 | + // Already locked. |
| 40 | + mutex.count++ |
| 41 | + return 1 // pdTRUE |
| 42 | + } |
| 43 | + // Not yet locked. |
| 44 | + mutex.lock.Lock() |
| 45 | + mutex.task = task.Current() |
| 46 | + return 1 // pdTRUE |
| 47 | +} |
| 48 | + |
| 49 | +//export xSemaphoreGiveRecursive |
| 50 | +func xSemaphoreGiveRecursive(xMutex C.SemaphoreHandle_t) C.BaseType_t { |
| 51 | + println("give recursive") |
| 52 | + mutex := (*Semaphore)(unsafe.Pointer(xMutex)) |
| 53 | + if mutex.task == task.Current() { |
| 54 | + // Already locked. |
| 55 | + mutex.count-- |
| 56 | + if mutex.count == 0 { |
| 57 | + mutex.lock.Unlock() |
| 58 | + } |
| 59 | + return 1 // pdTRUE |
| 60 | + } |
| 61 | + panic("xSemaphoreGiveRecursive: not locked by this task") |
| 62 | +} |
0 commit comments