Hey there together,
I need a little bit help pinpointing me to what I’m doing wrong. I’m trying to using a detached thread to be able to call my dispatch function in a non blocking loop.
I’m starting my thread with
std::thread dispatcher(startDispatch,
std::ref(simConnection),
std::ref(stopThread),
std::ref(dispatchIsRunning));
dispatcher.detach();
and call my translation unit which handels the dispatch calls and the dispatch itself (so it’s not running in main())
My loop looks like this
void startDispatch(SimConnection &simConnection,
std::atomic_bool &stopThread,
std::atomic_bool &isRunning)
{
isRunning = true;
int counter = 0;
isConnected = simConnection.isConnected();
quit = 0;
HANDLE hDispatchSimConnect = simConnection.getSimConnect();
HRESULT hr;
while (quit == 0 && !stopThread)
{
hr = SimConnect_CallDispatch(hDispatchSimConnect, dispatch, nullptr);
counter++;
if (counter >= 30)
{
quit = 1;
}
// below should be used in a later state to quit the loop / thread when the connection to SimConnect is lost
if (isConnected != simConnection.isConnected())
{
simConnection.setIsConnected(FlyShare::isConnected);
}
std::lock_guard<std::mutex> guard(mtx);
// for now hold at least 1 sec for each iteration
Sleep(1000);
}
isRunning = false;
}
At the end of my main() I’ll await the thread with
stopThread = true;
while (dispatchIsRunning)
{
continue;
}
This is most likely a temporary solution on my way to a proof of concept and is just a CLI implementation (I want to use a GUI later on when I am able to handle the most basic test cases).
My problem is that after compiling in Visual Studio the CLI runs just fine (without being able to connect as I have my sim on another machine, os this is expected).
As soon as I run the .exe with my sim running it runs for ~ 3 seconds after which it silently dies (just closes).
I testwise slept for 2 secs before calling the thread which then showed that my loop actually does it’s job, BUT
- when I remove SimConnect_CallDispatch the script works and the loop runs flawlessly
- when I use .join() instead of .detach() (which is undesired as it is blocking) the loop also works
Could perhaps somebody explain to me what is going on here? I have a 10 sec sleep at the end of my main to keep the CLI open during testing / debugging until switching to a GUI which suits my needs as I’m just checking if the communication works in different parts. This 10 sec sleep is also ignored combining a detached thread with DispatchCall.
There is much room for improvement here, e.g. a better way to hold the loop execution other than sleep but my goal right now only is to be able to use the polling loop.
Thanks in advance,
Phil