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; });



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

    while (true) {
        condition = canRun();

        if (condition) {
            b_can_execute = true;
        else {
            b_can_execute = false;


    b_add_done = true;

int main() { 

    std::thread canExec(canExecute);
    std::thread mainExec(mainExection);


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

Listing Addresses App Built with React