fix race conditions in slowticker... thanks to raldrich for finding one of them
authorJim Morris <morris@wolfman.com>
Tue, 17 Jun 2014 06:10:24 +0000 (23:10 -0700)
committerJim Morris <morris@wolfman.com>
Tue, 17 Jun 2014 06:10:24 +0000 (23:10 -0700)
src/libs/SlowTicker.cpp
src/libs/SlowTicker.h

index a66b313..d54e50c 100644 (file)
@@ -27,14 +27,8 @@ SlowTicker::SlowTicker(){
     max_frequency = 0;
     global_slow_ticker = this;
 
-    // Configure the actual timer
-    LPC_SC->PCONP |= (1 << 22);     // Power Ticker ON
-    LPC_TIM2->MR0 = 10000;          // Initial dummy value for Match Register
-    LPC_TIM2->MCR = 3;              // Match on MR0, reset on MR0
-    LPC_TIM2->TCR = 1;              // Enable interrupt
-    NVIC_EnableIRQ(TIMER2_IRQn);    // Enable interrupt handler
 
-    // ISP button
+    // ISP button FIXME: WHy is this here?
     ispbtn.from_string("2.10")->as_input()->pull_up();
 
     // TODO: What is this ??
@@ -43,6 +37,13 @@ SlowTicker::SlowTicker(){
 
     g4_ticks = 0;
     g4_pause = false;
+
+    // Configure the actual timer after setup to avoid race conditions
+    LPC_SC->PCONP |= (1 << 22);     // Power Ticker ON
+    LPC_TIM2->MR0 = 10000;          // Initial dummy value for Match Register
+    LPC_TIM2->MCR = 3;              // Match on MR0, reset on MR0
+    LPC_TIM2->TCR = 1;              // Enable interrupt
+    NVIC_EnableIRQ(TIMER2_IRQn);    // Enable interrupt handler
 }
 
 void SlowTicker::on_module_loaded(){
index 2e8204f..133dd78 100644 (file)
@@ -33,19 +33,25 @@ class SlowTicker : public Module{
         void set_frequency( int frequency );
         void tick();
         // For some reason this can't go in the .cpp, see :  http://mbed.org/forum/mbed/topic/2774/?page=1#comment-14221
+        // TODO replace this with std::function()
         template<typename T> Hook* attach( uint32_t frequency, T *optr, uint32_t ( T::*fptr )( uint32_t ) ){
             Hook* hook = new Hook();
             hook->interval = int(floor((SystemCoreClock/4)/frequency));
             hook->attach(optr, fptr);
             hook->countdown = hook->interval;
+
+            // to avoid race conditions we must stop the interupts before updating this non thread safe vector
+            __disable_irq();
             if( frequency > this->max_frequency ){
                 this->max_frequency = frequency;
                 this->set_frequency(frequency);
             }
             this->hooks.push_back(hook);
+            __enable_irq();
             return hook;
         }
 
+    private:
         bool flag_1s();
 
         vector<Hook*> hooks;