One of the most annoying things with database calls is creating a thread to process the call.
Here’s some psuedocode to illustrate the issue:
void QueryDB() {
CreateThread(SelectResults, callback);
}
int SelectResults(Callback *callback) {
result = Process(“select * from db”);
callback(result);
}
void Callback(Result *result) {
printf(“result is %i”, result);
}
Doing the same thing inline is much easier. It’s one function rather than 3, and you also have context about the call.
void QueryDB() {
result = Process(“select * from db”);
printf(“result is %i”, result);
}
However, it blocks your entire program.
I came up with an “InlineFunctorProcessor” system that has the benefits of both. It allows you to do blocking calls all within the context of one function, but runs the blocking call in a thread while your program continues running.
printf(“Enter file to read: “);
ReadFileFunctor *rff = new ReadFileFunctor;
gets(rff->fn);
// Nonblocking, but processes as easily as if it were
YieldOnFunctor(rff);
if (rff->data)
printf(“Got file data\n%s\n”, rff->data);
else
printf(“Open failed\n”);
delete rff;
The way the system works is through recursion, thus saving prior calls on the stack. The yield function calls the main application update loop – or any other function you want to call while the function is processing. That function is responsible for calling InlineFunctorProcessor::UpdateIFP(), which if it returns true, the function should also return.
Here’s the code for the base class:
Header
Source
Here’s a solution that demonstrates the functionality
Download