brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 1 | #ifdef __VXWORKS__ |
| 2 | #include <taskLib.h> |
| 3 | #else |
| 4 | #include <sched.h> |
| 5 | #endif |
| 6 | |
John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame] | 7 | #include "aos/type_traits/type_traits.h" |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 8 | |
| 9 | // It doesn't use pthread_once, because Brian looked at the pthreads |
| 10 | // implementation for vxworks and noticed that it is completely and entirely |
| 11 | // broken for doing just about anything (including its pthread_once). It has the |
Brian Silverman | 14fd0fb | 2014-01-14 21:42:01 -0800 | [diff] [blame] | 12 | // same implementation under linux for simplicity. |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 13 | |
| 14 | namespace aos { |
| 15 | |
| 16 | // Setting function_ multiple times would be OK because it'll get set to the |
| 17 | // same value each time. |
| 18 | template<typename T> |
| 19 | Once<T>::Once(Function function) |
| 20 | : function_(function) { |
| 21 | static_assert(shm_ok<Once<T>>::value, "Once should work in shared memory"); |
| 22 | } |
| 23 | |
| 24 | template<typename T> |
| 25 | void Once<T>::Reset() { |
Brian Silverman | 4968c20 | 2014-05-19 17:04:02 -0700 | [diff] [blame] | 26 | __atomic_store_n(&run_, false, __ATOMIC_SEQ_CST); |
| 27 | __atomic_store_n(&done_, false, __ATOMIC_SEQ_CST); |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 28 | } |
| 29 | |
| 30 | template<typename T> |
| 31 | T *Once<T>::Get() { |
Brian Silverman | 4968c20 | 2014-05-19 17:04:02 -0700 | [diff] [blame] | 32 | if (__atomic_exchange_n(&run_, true, __ATOMIC_RELAXED) == false) { |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 33 | result_ = function_(); |
Brian Silverman | 4968c20 | 2014-05-19 17:04:02 -0700 | [diff] [blame] | 34 | __atomic_store_n(&done_, true, __ATOMIC_RELEASE); |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 35 | } else { |
Brian Silverman | 4968c20 | 2014-05-19 17:04:02 -0700 | [diff] [blame] | 36 | while (!__atomic_load_n(&done_, __ATOMIC_ACQUIRE)) { |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 37 | sched_yield(); |
brians | 2fdfc07 | 2013-02-26 05:35:15 +0000 | [diff] [blame] | 38 | } |
| 39 | } |
| 40 | return result_; |
| 41 | } |
| 42 | |
| 43 | } // namespace aos |