Question

The problem: First off, this is a simplified example of my problem, and it is really part of a large framework already programmed by someone else in which i have to adapt my code into.

I have 3 functions. Two of the functions (function1 and function2) are being called by other parts of the program both asynchronously and synchronously. My last function (function3) runs continuously, like a while loop, and the only thing it does is to fire an event code on each code iteration. I only want this last function to run whenever one of the two other functions have completed an iteration/been called. I can not change how/when they are called, i can only block the execution of the code and unblock it.

I am fairly new to c++ and i have tried solving this using a mutex, but i have had no luck. I can add the code, but it really is just like i explained.

void function1(){  // this function is called by other parts of the program
//some code
}

void funtion2(){  //this function is also called by other parts of the program
//some other code
}

void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it

fireEvent();//fires an event to run some other code
}

So, function3 runs all the time unless blocked, and i would only like to run the function every time one of the other functions have had one run-through. Like i said before, i can not call function3 myself, i can only manipulate the code in the function.

What is the best way of going about this?

After intense googleing i have only come up with conditional variables, semaphore and mutex, but i don't know enough about them to know how i can implement it correctly.

Any help/input/tip is greatly appreciated.

Was it helpful?

Solution

A straigtforward way would be like this:

mutex g_mutex;
condition_variable g_cond;
bool flag = false;
void function1(){ // this function is called by other parts of the program
    //some code
    lock_guard<mutex> lock(g_mutex);
    flag = true;
    g_cond.notify_one();
}

void funtion2(){ //this function is also called by other parts of the program
    //some other code
    lock_guard<mutex> lock(g_mutex);
    flag = true;
    g_cond.notify_one();
}

void function3(){ //this function runs continuously, similar to a while loop with a 1ms sleep in it
    {
        unique_lock<mutex> lock(g_mutex);
        g_cond.wait(lock, []{return flag;}); // wait here until func1 or func2 have been called
        flag = false;
    }
    fireEvent();//fires an event to run some other code
}

int main() {
// your code goes here
return 0;
}

But this will block your function3 until one of the other twos are called. So it is a change of the behaviour and it adds additional lock contention.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top