in

Is it possible to run a thread, that executes a function in a loop, only when a condition is met, which is also checked in a loop?


I want to check in one thread A if a condition is met,
if the condition is true I want another thread B to execute my code, once that is done, I want thread B to wait until that condition is true again, then it executes the code again, and so on.
There is enough time to execute all the code in thread B before the condition is false.
Basically thread A runs at normal speed, thread B only runs when thread A tells it it can run.
And I don’t want to spawn a new thread B all the time, it shouldn’t stop, it should just execute it’s code and then wait until it’s allowed to execute it’s code again.

How can I do that? This is what I have so far, but I don’t how to run mainExecution() in this type of loop.


std::mutex m;
std::condition_variable cv_can_execute;

// these boolean variables are needed to detect Spurious wakeups
bool b_can_execute = false;


void mainExection() {
    std::unique_lock lk(m);
    cv_can_execute.wait(lk, [] { return b_can_execute; });

    doSomethingElse();
    

    
}

void canExecute() {
    std::unique_lock lk(m); 


    while (true) {
        condition = canRun();

        if (condition) {
            b_can_execute = true;
            cv_can_execute.notify_all();
        }
        else {
            b_can_execute = false;
        }

    }

   
    b_add_done = true;
    cv_add_done.notify_all();
}

int main() { 
    

    std::thread canExec(canExecute);
    std::thread mainExec(mainExection);
   
    canExec.join();
    mainExec.join();
  
}



Source: https://stackoverflow.com/questions/70629458/is-it-possible-to-run-a-thread-that-executes-a-function-in-a-loop-only-when-a

ESIC MTS Syllabus 2022, ESIC MTS Exam Pattern for Prelims & Mains

Listing Addresses App Built with React