James Kuszmaul | 4f3ad3c | 2019-12-01 16:35:21 -0800 | [diff] [blame] | 1 | /*----------------------------------------------------------------------------*/ |
| 2 | /* Copyright (c) 2019 FIRST. All Rights Reserved. */ |
| 3 | /* Open Source Software - may be modified and shared by FRC teams. The code */ |
| 4 | /* must be accompanied by the FIRST BSD license file in the root directory of */ |
| 5 | /* the project. */ |
| 6 | /*----------------------------------------------------------------------------*/ |
| 7 | |
| 8 | #include "hal/Main.h" |
| 9 | |
| 10 | #include <wpi/condition_variable.h> |
| 11 | #include <wpi/mutex.h> |
| 12 | |
| 13 | static void DefaultMain(void*); |
| 14 | static void DefaultExit(void*); |
| 15 | |
| 16 | static bool gHasMain = false; |
| 17 | static void* gMainParam = nullptr; |
| 18 | static void (*gMainFunc)(void*) = DefaultMain; |
| 19 | static void (*gExitFunc)(void*) = DefaultExit; |
| 20 | static bool gExited = false; |
| 21 | struct MainObj { |
| 22 | wpi::mutex gExitMutex; |
| 23 | wpi::condition_variable gExitCv; |
| 24 | }; |
| 25 | |
| 26 | static MainObj* mainObj; |
| 27 | |
| 28 | static void DefaultMain(void*) { |
| 29 | std::unique_lock lock{mainObj->gExitMutex}; |
| 30 | mainObj->gExitCv.wait(lock, [] { return gExited; }); |
| 31 | } |
| 32 | |
| 33 | static void DefaultExit(void*) { |
| 34 | std::lock_guard lock{mainObj->gExitMutex}; |
| 35 | gExited = true; |
| 36 | mainObj->gExitCv.notify_all(); |
| 37 | } |
| 38 | |
| 39 | namespace hal { |
| 40 | namespace init { |
| 41 | void InitializeMain() { |
| 42 | static MainObj mO; |
| 43 | mainObj = &mO; |
| 44 | } |
| 45 | } // namespace init |
| 46 | } // namespace hal |
| 47 | |
| 48 | extern "C" { |
| 49 | |
| 50 | void HAL_SetMain(void* param, void (*mainFunc)(void*), |
| 51 | void (*exitFunc)(void*)) { |
| 52 | gHasMain = true; |
| 53 | gMainParam = param; |
| 54 | gMainFunc = mainFunc; |
| 55 | gExitFunc = exitFunc; |
| 56 | } |
| 57 | |
| 58 | HAL_Bool HAL_HasMain(void) { return gHasMain; } |
| 59 | |
| 60 | void HAL_RunMain(void) { gMainFunc(gMainParam); } |
| 61 | |
| 62 | void HAL_ExitMain(void) { gExitFunc(gMainParam); } |
| 63 | |
| 64 | } // extern "C" |