Add Control over recursive function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dipak000
    New Member
    • Nov 2014
    • 4

    #1

    Add Control over recursive function

    Hello All, below i attached a code where i need a control on recursive function. Means, it should wait for my button press signal to move further.

    Code:
    void PlaySongs::performance(int step){
    
    step++;
    
    if (waitForInterruptSys (iOnePin, -1) >0)
    {
       cout<<"Push Button is pressed"<<endl;
    
       SoundNamespace::SoundProject::SoundProject project;
    
       project.Init();
       project.InitSound();
       
       project.StartInterruptThreads();
       project.LoadProject();
       project.AdjustSounds();
       project.LoadSounds(true);
       project.StartPlayingSounds();
       
       cout << "Initialization finished." << endl;
    
    
    // Some C++ control statement NEEDS here  <--
    
    /* here i need control, so that, after button pressed on bread board, it should move further
    i.e. perform next statements, otherwise wait infinite time. something like cvWaitKey(0) from
    opencv. Interrupt detected by (waitForInterruptSys (iOnePin, -1) >0). like written above. */.
    
    if(step==3)
         return;
    else
        performance(step);
     
    }
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Your easiest solution is to use a global static variable.

    Say you put 0 into the variable and then the recursive function is called. The recursive function initially goes into a loop which tests the variable. When the value is , say 1, the function proceeds. Each recursion call will test the same variable, which will be 1, and so the recursion will proceed normally.

    At the end, the caller of the recursion changes the value back to 0. The recursive function should not change the variable.

    This is a "poor man's" version of a Singleton object. It's OK for student work but not for actual production code.

    Unfortunately, while that recursive function is in a loop which tests that global variable, it has tied up the thread of execution so the caller of the recursion can't get in to change the variable. Therefore, you call your recursive function on a separate thread. Here you need to research, for the OS you are using, how to do multithreading.

    Worse, with both the recursive function thread and the caller thread of the recursion trying to access that global variable at the same time, you can create a race condition that can lock up your program. So you will also need to learn how to set up, and use, a critical section to surround access to that variable so that only one thread at a time can access it.

    What OS are you using?

    Comment

    Working...