I'm making a dll that has to respond to an application's requests. One of the application's requirements is that a call should not take long to complete.
Say, I have a function foo(), which is called by the host application:
int foo(arg){
// some code i need to execute, say,
LengthyRoutine();
return 0;
}
Lets say, foo has to perform a task (or call a function) that is certain to take a long time. The application allows me to set a wait variable; if this variable is non-zero when foo returns, it calls foo again and again (resetting the wait variable before each call) until wait is returned 0.
What's the best approach to this?
Do I go:
int foo(arg){
if (inRoutine == TRUE) {
wait = 1;
return 0;
} else {
if (doRoutine == TRUE) {
LengthyRoutine();
return 0;
}
}
return 0;
}
This doesn't really solve the problem that LengthyRoutine is gonna take a long time to complete. Should I spawn a thread of some sort that updates inRoutine depending on whether or not it has finished its task?
Thanks..
Spawning another thread is pretty much the best way to do it, just make sure you set the result variables before you set the variable that says you're finished to avoid race conditions. If this is called often you might want to spawn a worker thread ahead of time and reuse it to avoid thread start overhead.
There is another possible solution, do part of the work each time the function is called, however this spends more time in the DLL and probably isn't optimal, as well as being more complex to implement the worker code for most algos.