So I have a loop that is running and (keeping a connection to the server).
I want to send messages to that server in a (4) seconds interval wihout losing the connection.
How can I have Sleep()for that specific Function without stopping other loops?
1 2 3 4 5 6 7 8 9 10 11 12 13
void CMI::SendLoop()
{
while (Sending)
{
std::this_thread::sleep_for(seconds(4)); //connection is lost
SendMessage("Im here");
}
}
If it's an event driven system like windows then I believe there's a way to schedule an event for the future. Then you're keep-alive could just process the event and schedule another.
#include <future>
#include <thread>
#include <iostream>
#include <chrono>
#include <utility>
void NetworkLoop(std::future<bool> condition)
{
// Messeage sending procedure
auto SendMessage = [](constchar* message)
{
std::cout << message << std::endl;
};
// main thread will signal end of program to this thread trough this variable
auto status = std::future_status::deferred;
// Keep sending packets until program exit every 2 seconds
while (status != std::future_status::ready)
{
SendMessage("Im here!");
status = condition.wait_for(std::chrono::seconds(2));
}
}
int main()
{
// Create communication channel between this and network thread
std::promise<bool> promise;
std::future<bool> condition = promise.get_future();
// Create network thread
std::thread network(NetworkLoop, std::move(condition));
// Main program runs for 10 seconds
// it does nothing special by default but it could so here...
std::this_thread::sleep_for(std::chrono::seconds(10));
// Tell network thread to stop
promise.set_value(true);
// Join thread
network.join();
std::cout << "Program is finished!" << std::endl;
}
another way is, if you already have like a main loop in your main program code, just put a timer there, and if enough time has passed, do the activity.
that changes the loop to
get current time
loop
{
things;
if current time - last time > time to wait
{
send keep alive message
update last time
}
more things;
}
single threaded programs are starting to be a thing of the past, but if you were on an embedded system with 1 cpu or something, or just starting out and don't want to tackle threading yet, etc this will do it.
text eds are often threaded now, mixed bag on those.
quantum computers are so far past the end of my life I can't worry about it :) But many things will go out of scope. A lot of security goes out the window, in theory.
as I understand the theory (which is not well) they can do anything the old fashioned way, its just not ideal for the hardware.