Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 1 | // Copyright (c) FIRST and other WPILib contributors. |
| 2 | // Open Source Software; you can modify and/or share it under the terms of |
| 3 | // the WPILib BSD license file in the root directory of this project. |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 4 | |
| 5 | #include "hal/Main.h" |
| 6 | |
| 7 | #include <wpi/condition_variable.h> |
| 8 | #include <wpi/mutex.h> |
| 9 | |
| 10 | static void DefaultMain(void*); |
| 11 | static void DefaultExit(void*); |
| 12 | |
| 13 | static bool gHasMain = false; |
| 14 | static void* gMainParam = nullptr; |
| 15 | static void (*gMainFunc)(void*) = DefaultMain; |
| 16 | static void (*gExitFunc)(void*) = DefaultExit; |
| 17 | static bool gExited = false; |
| 18 | struct MainObj { |
| 19 | wpi::mutex gExitMutex; |
| 20 | wpi::condition_variable gExitCv; |
| 21 | }; |
| 22 | |
| 23 | static MainObj* mainObj; |
| 24 | |
| 25 | static void DefaultMain(void*) { |
| 26 | std::unique_lock lock{mainObj->gExitMutex}; |
| 27 | mainObj->gExitCv.wait(lock, [] { return gExited; }); |
| 28 | } |
| 29 | |
| 30 | static void DefaultExit(void*) { |
| 31 | std::lock_guard lock{mainObj->gExitMutex}; |
| 32 | gExited = true; |
| 33 | mainObj->gExitCv.notify_all(); |
| 34 | } |
| 35 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 36 | namespace hal::init { |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 37 | void InitializeMain() { |
| 38 | static MainObj mO; |
| 39 | mainObj = &mO; |
| 40 | } |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 41 | } // namespace hal::init |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 42 | |
| 43 | extern "C" { |
| 44 | |
| 45 | void HAL_SetMain(void* param, void (*mainFunc)(void*), |
| 46 | void (*exitFunc)(void*)) { |
| 47 | gHasMain = true; |
| 48 | gMainParam = param; |
| 49 | gMainFunc = mainFunc; |
| 50 | gExitFunc = exitFunc; |
| 51 | } |
| 52 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 53 | HAL_Bool HAL_HasMain(void) { |
| 54 | return gHasMain; |
| 55 | } |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 56 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 57 | void HAL_RunMain(void) { |
| 58 | gMainFunc(gMainParam); |
| 59 | } |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 60 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 61 | void HAL_ExitMain(void) { |
| 62 | gExitFunc(gMainParam); |
| 63 | } |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 64 | |
| 65 | } // extern "C" |