Perform function at certain clock time - c++

I would like the user to input a time e.g. 1400h - which will then cause a function to run at 1400h.
How can I do this?
Context: I have a client-server program that works on the same computer - and I need several nodes to send messages simultaneously (which is the function as above)
edit: I do not want to use a sleep() function, ideally, as the issue is that the clients will be started at different times and it is much neater as a solution to call something that causes the function to execute at 1400h.

You can use std::this_thread::sleep_until, e.g.
void main()
{
auto fire_time = /**/;
std::thread thread([&]
{
std::this_thread::sleep_until(fire_time);
fire();
});
thread.join();
}
You can refactor that into a helper function, which is probably what you are looking for:
template<class Func, class Clock, class Duration>
void run_at(Func&& func, const std::chrono::time_point<Clock,Duration>& sleep_time)
{
std::thread(std::bind([&](const Func& func)
{
std::this_thread::sleep_until(sleep_time);
func();
}, std::move(func)))
.detach();
}

If the program is running the entire time, use a function such as sleep to wait the amount of time between now and 1400h. You might need to do this in a separate thread to allow the program to do other things, or replace the sleep with an event loop timeout (if the program is event-loop-based).
If the program must exit, then you must use a system facility, such as at on Unix, to arrange the program to be restarted and code to be executed at the specified time.

I believe you need a some kind of task manager. That's a basic model. Breeding sleeping threads is very wrong way to do that job. A single manager will know when to run a next task. How to run a task is another question. You can make new thread per task if you want them to be interactive. Or you can serialize them and run from within the manager thread.

Related

Create threads dynamically depending on time needs of single tasks

Say I have a list of callable objects like
std::list<std::shared_ptr<Callable>> tasks;
and the task is to run them all in an infinite loop, say
void run_all(const bool& abort){
while(true){
for(const auto& ptr : tasks){
if (abort) return;
(*ptr)();
}
}
}
This is fine as long as every "task" finishes after short time. Now I'd like to add the requirement that whenever a task needs more time than a specific threshold, a new thread should be created so that the other tasks do not have do wait for a specific long running task.
The simplest solution regarding code complexity I can think of at the moment would be creating a thread for each task:
void run_all(const bool& abort){
auto job = [&](std::shared_ptr<Callable> task){
while (!abort){
(*task)();
}
};
std::list<std::thread> threads;
for(auto& ptr : tasks){
threads.emplace_back(job, ptr);
}
for(auto& t : threads){
t.join();
}
}
But this might create inappropriate many threads.
What is an appropriate way to implement running the tasks and create threads dynamically depending on how long a tasks needs to be finished? Say we have got some
std::chrono::duration threshold;
and the goal is to run the first task and continue with the next afterwards if the first one takes no longer than threshold until finish, but create a new thread to run the rest of the tasks in parallel, if the first task does not finish before threashold. The generalized goal is:
If there is no task that has been finished in some thread so that another task began to run during the certain period of time threshold, then a new thread should be created so that other tasks which may potentially run in very short time do not have to wait.
If there are more than 3 threads that finish at least one task per period threshold, one of them should be joined.
There may be tasks that itself run ad infinitum. This should have no effect on the other tasks.
What could be an appropriate implementation satisfying these requirements or at least doing something related or at least a concept of an implementation?
Or is it completely fine to just create a bunch of threads? (I think about running such an application on a low performance machine like Raspberry Pi and a set of 50 to 300 tasks that should be treated.)

Implementing a custom async task type and await

I am developing a C++ app in which i need to receive messages from an MQ and then parsing them according to their type and for a particular reason I want to make this process (receiving a single message followed by processing it) asynchronous. Since, I want to keep things as simple as possible in a way that the next developer would have no problem continuing the code, I have written a very small class to implement Asynchrony.
I first raise a new thread and pass a function to the thread:
task = new thread([&] {
result = fn();
isCompleted = true;
});
task->detach();
and in order to await the task I do the following:
while (!isCompleted && !(*cancelationToken))
{
Sleep(5);
}
state = 1; // marking the task as completed
So far there is no problem and I have not faced any bug or error but I am not sure if this is "a good way to do this" and my question is focused on determining this.
Read about std::future and std::async.
If your task runs in another core or processor, the variable isCompleted may become un-synchronized having two copies in core cache. So you may be waiting more than needed.
If you have to wait for something it is better to use a semaphore.
As said in comments, using standard methods is better anyway.

Play Framework 2.4 Sequential run of multiple Promises

I have got a Play 2.4 (Java-based) application with some background Akka tasks implemented as functions returning Promise.
Task1 downloads bank statements via bank Rest API.
Task2 processes the statements and pairs them with customers.
Task3 does some other processing.
Task2 cannot run before Task1 finishes its work. Task3 cannot run before Task2. I was trying to run them through sequence of Promise.map() like this:
protected F.Promise run() throws WebServiceException {
return bankAPI.downloadBankStatements().map(
result -> bankProc.processBankStatements().map(
_result -> accounting.checkCustomersBalance()));
}
I was under an impression, that first map will wait until Task1 is done and then it will call Task2 and so on. When I look into application (tasks are writing some debug info into log) I can see, that tasks are running in parallel.
I was also trying to use Promise.flatMap() and Promise.sequence() with no luck. Tasks are always running in parallel.
I know that Play is non-blocking application in nature, but in this situation I really need to do things in right order.
Is there any general practice on how to run multiple Promises in selected order?
You're nesting the second call to map, which means what's happening here is
processBankStatements
checkCustomerBalance
downloadBankStatements
Instead, you need to chain them:
protected F.Promise run() throws WebServiceException {
return bankAPI.downloadBankStatements()
.map(statements -> bankProc.processBankStatements())
.map(processedStatements -> accounting.checkCustomersBalance());
}
I notice you're not using result or _result (which I've renamed for clarity) - is that intentional?
Allright, I found a solution. The correct answer is:
If you are chaining multiple Promises in the way I do. That means, in return of map() function you are expecting another Promise.map() function and so on, you should follow these rules:
If you are returning non-futures from mapping, just use map()
If you are returning more futures from mapping, you should use flatMap()
The correct code snippet for my case is then:
return bankAPI.downloadBankStatements().flatMap(result -> {
return bankProc.processBankStatements().flatMap(_result -> {
return accounting.checkCustomersBalance().map(__result -> {
return null;
});
});
});
This solution was suggested to me a long time ago, but it was not working at first. The problem was, that I had a hidden Promise.map() inside function downloadBankStatements() so the chain of flatMaps was broken in this case.

Is it possible to change the tick count value returned from GetTickCount()?

I'm trying to do some testing and it requires the Windows system to be up and running for 15 Real-Time minutes before a certain action can ever occur. However, this is very time consuming to HAVE to wait the 15 real-time minutes.
Is there a way to change the value GetTickCount() returns so as to make it appear that the system has been running for 15 real-time minutes?
Edit: There is an app that does something close to what I want, but it doesn't quite seem to work and I have to deal with hexadecimal values instead of straight decimal values: http://ysgyfarnog.co.uk/utilities/AdjustTickCount/
Not directly.
Why not just mock the call, or replace the chunk of code that does the time check with a strategy object?
struct Waiter
{
virtual void Wait() = 0;
virtual ~Waiter() {};
};
struct 15MinWaiter : public Waiter
{
virtual void Wait()
{
//Do something that waits for 15 mins
}
};
struct NothingWaiter : public Waiter
{
virtual void Wait()
{
//Nill
}
};
You could do similar to mock out a call to GetTickCount, but doing this at the higher level of abstraction of whatever is doing the wait is probably better.
For debugging purposes, you can just replace all the calls to GetTickCount() with _GetTickCount(), which can implement to return with GetTickCount() or GetTickCount()+15min, depending whether or not you are debugging.
Why not make it one minute, confirm it works, then change it back to fifteen?
You could do something quite hideous like #define GetTickCount() MyReallyEvilReplacement().
You can use the Application Verifier provided with the Windows SDK to run your app with the "Miscellaneous > TimeRollOver" test. It will fake a tick count which starts at a time that will overflow after a short moment.
Another possibility is to to hibernate / hybrid shutdown / sleep a Windows system, then boot to the BIOS, change the date time to something you require, like add 30 days if you want to test unsigned tick counts. When Windows boots again, it has no way of detecting the appropiate time since the computer really started previously, and thinks it is running for 30 more days. It is important to use sleep / hibernate / hybrid shutdown (the latter being the default since Windows 8), not a full shutdown, as the up time is otherwise reset.
Yet another possibility could be to hook imports of GetTickCount to your own code and let it return arbitrary results.

Handling Interrupt in C++

I am writing a framework for an embedded device which has the ability to run multiple applications. When switching between apps how can I ensure that the state of my current application is cleaned up correctly? For example, say I am running through an intensive loop in one application and a request is made to run a second app while that loop has not yet finished. I cannot delete the object containing the loop until the loop has finished, yet I am unsure how to ensure the looping object is in a state ready to be deleted. Do I need some kind of polling mechanism or event callback which notifies me when it has completed?
Thanks.
Usually if you need to do this type of thing you'll have an OS/RTOS that can handle the multiple tasks (even if the OS is a simple homebrew type thing).
If you don't already have an RTOS, you may want to look into one (there are hundreds available) or look into incorporating something simple like protothreads: http://www.sics.se/~adam/pt/
So you have two threads: one running the kernel and one running the app? You will need to make a function in your kernel say ReadyToYield() that the application can call when it's happy for you to close it down. ReadyToYield() would flag the kernel thread to give it the good news and then sit and wait until the kernel thread decides what to do. It might look something like this:
volatile bool appWaitingOnKernel = false;
volatile bool continueWaitingForKernel;
On the app thread call:
void ReadyToYield(void)
{
continueWaitingForKernel = true;
appWaitingOnKernel = true;
while(continueWaitingForKernel == true);
}
On the kernel thread call:
void CheckForWaitingApp(void)
{
if(appWaitingOnKernel == true)
{
appWaitingOnKernel = false;
if(needToDeleteApp)
DeleteApp();
else
continueWaitingForKernel = false;
}
}
Obviously, the actual implementation here depends on the underlying O/S but this is the gist.
John.
(1) You need to write thread-safe code. This is not specific to embedded systems.
(2) You need to save state away when you do a context switch.