Reputation: 359
My code is:
while (DAQ is ON) {
do stuff on vars;
if(f(vars) > thr)
update vars;
}
The if condition will be triggered only occasionally and will update all the variables used in the earlier section of the while loop. The overall loop is usually running in real time (as needed) but falls behind when the if condition also needs to be run. How can I run the if condition in a separate thread? It can take all the time it needs, it's okay if the update happens after a delay. I just want the rest of the while loop to run in real time and for the vars to get updated whenever the "if" thread gets done.
Context: C++/JUCE framework, real time signal processing.
Upvotes: 0
Views: 1007
Reputation: 576
I'll assume that you have at least 2 cores to work with here. Otherwise, multithreading won't help you much, if at all. I'm using the C++11 multithreading semantics here, so you'll to enable the C++11 language specs in your compiler:
#include <condition_variable>
#include <thread>
#include <mutex>
using namespace std;
condition_variable cv;
mutex mtx;
bool ready = false;
void update_vars() {
while( true ) {
// Get a unique lock on the mutex
unique_lock<mutex> lck(mtx);
// Wait on the condition variable
while( !ready ) cv.await( mtx );
// When we get here, the condition variable has been triggered and we hold the mutex
// Do non-threadsafe stuff
ready = false;
// Do threadsafe stuff
}
}
void do_stuff() {
while( true ) {
// Do stuff on vars
if ( f(vars) ) {
// Lock the mutex associated with the condition variable
unique_lock<mutex> lck(mtx);
// Let the other thread know we're ready for it
ready = true;
// and signal the condition variable
cv.signal_all();
}
while( ready ) {
// Active wait while update_vars does non-threadsafe stuff
}
}
}
int main() {
thread t( update_vars );
do_stuff()
}
What the above code snippet does is creates a secondary thread running update vars, which will hang around and wait until the main thread (running do_stuff) signals it through the condition variable.
PS, you could probably also do this with futures, but I've not worked with those enough to answer based on those.
Upvotes: 2