I think I am right in thinking that if I have a program like this which sets up a callback function.
void MyCallbackFunction(char* data) {
cout << "some data arrived: " << data << endl;
}
int main(){
//sets up callback
SetDispatchFunction(&MyCallbackFunction));
while(1==1) {
sleep(1000);
}
return 0;
}
then because this is a single threaded program and execution will be always handling the while loop, there is no way for the program to handle the MyCallbackFunction handler?
If so, assuming I don’t want to use multiple threads, what options do I have to allow processing of the callback function?
I decided to include a real example to demonstrate.
#include <iostream>
using namespace std;
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
BOOL CALLBACK EnumChildProc(HWND hwndChild, LPARAM lParam)
{
char szText[100] = {0};
GetWindowText(hwndChild, szText, 100);
if (lstrlen(szText) < 1) return true;
cout << "Window text: " << szText << endl;
return TRUE;
}
int main(int argc, char* argv[])
{
//latch onto Google Chrome if running
HWND windowHandle = FindWindow("Chrome_WidgetWin_0", 0);
if(windowHandle)
EnumChildWindows(windowHandle, EnumChildProc, 0);
//loop so program doesn't stop
while(1==1) {
Sleep(2000);
}
return 0;
}
The callback function usually gets called in the thread spawned by the entity you register with, You will need some sort of an signalling mechanism, by which you make your main thread aware of the callback. It is always advisable to not perform your processing in the thread, instead one should switch the context and do the processing in one of their own threads.
Just consider as an Example:
Main thread blocks on a message Queue(or periodically checks for the same), waiting to read a message and in the callback function you post a message to this message queue.
You could also use an global protected by synchronization to achieve a similar functionality without message Queue.
However, If your program is strictly single threaded,then at some point of time the
whileloop will be interrupted and the callback function will get executed,wherein you can setup a global variable, which then can be checked by the while when it gets interrupted.Ofcourse,Synchronization will be needed.