Delay Tasks in a C++ Windows App (Sleep) - c++

I am currently writing a little Windows 10 app in VS 2015 in C++. I am trying to follow this guide:
https://msdn.microsoft.com/en-us/windows/uwp/get-started/create-a-basic-windows-10-app-in-cpp
Now I have a little loop that looks like this:
while (getline(file, line))
{
i++;
//std::this_thread::sleep_for(std::chrono::milliseconds(300));
//Sleep(300);
MyApp::MainPage::outBox->Text = ref new PLatform::String(to_wstring(i).c_str());}
I want the loop to wait a few hundred ms in order to continually change the content of a textbox. What the methods i tried achieved was that the output itself was delayed but the counting was continued, so that nothing changed until after the accumulated wait times. So the ouput goes from 0 to 50 after a few seconds instead of 0->1-2->3... every 300 ms. I thought that maybe this:
https://msdn.microsoft.com/de-de/library/hh194873(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1
Is a solution, but I cant get it to work in C++. The Class System::Threading has no member Task or Tasks...
Thanks in advance!

Related

Hard Realtime C++ for Robot Control

I am trying to control a robot using a template-based controller class written in c++. Essentially I have a UDP connection setup with the robot to receive the state of the robot and send new torque commands to the robot. I receive new observations at a higher frequency (say 2000Hz) and my controller takes about 1ms (1000Hz) to calculate new torque commands to send to the robot. The problem I am facing is that I don't want my main code to wait to send the old torque commands while my controller is still calculating new commands to send. From what I understand I can use Ubuntu with RT-Linux kernel, multi-thread the code so that my getTorques() method runs in a different thread, set priorities for the process, and use mutexes and locks to avoid data race between the 2 threads, but I was hoping to learn what the best strategies to write hard-realtime code for such a problem are.
// main.cpp
#include "CONTROLLER.h"
#include "llapi.h"
void main{
...
CONTROLLERclass obj;
...
double new_observation;
double u;
...
while(communicating){
get_newObs(new_observation); // Get new state of the robot (2000Hz)
obj.getTorques(new_observation, u); // Takes about 1ms to calculate new torques
send_newCommands(u); // Send the new torque commands to the robot
}
...
}
Thanks in advance!
Okay, so first of all, it sounds to me like you need to deal with the fact that you receive input at 2 KHz, but can only compute results at about 1 KHz.
Based on that, you're apparently going to have to discard roughly half the inputs, or else somehow (in a way that makes sense for your application) quickly combine the inputs that have arrived since the last time you processed the inputs.
But as the code is structured right now, you're going to fetch and process older and older inputs, so even though you're producing outputs at ~1 KHz, those outputs are constantly being based on older and older data.
For the moment, let's assume you want to receive inputs as fast as you can, and when you're ready to do so, you process the most recent input you've received, produce an output based on that input, and repeat.
In that case, you'd probably end up with something on this general order (using C++ threads and atomics for the moment):
std::atomic<double> new_observation;
std::thread receiver = [&] {
double d;
get_newObs(d);
new_observation = d;
};
std::thread sender = [&] {
auto input = new_observation;
auto u = get_torques(input);
send_newCommands(u);
};
I've assumed that you'll always receive input faster than you can consume it, so the processing thread can always process whatever input is waiting, without receiving anything to indicate that the input has been updated since it was last processed. If that's wrong, things get a little more complex, but I'm not going to try to deal with that right now, since it sounds like it's unnecessary.
As far as the code itself goes, the only thing that may not be obvious is that instead of passing a reference to new_input to either of the existing functions, I've read new_input into variable local to the thread, then passed a reference to that.

How to call a function every x seconds but be able to do stuff in the meantime

I'm building a tetris game and I need the pieces to fall every x seconds; something like:
while(true){
moveDown();
sleep(x)
}
The problem is, I need to be able to move the pieces left and right in the meantime, i.e., call a function while it's sleeping.
How can I do that in c++?
Both time and key presses can be events which can be used to wait on. On UNIXes you'd use something like poll() with a suitable time for timeout and the input device used to recognize key presses. On other systems there are similar facilities (I'm a UNIX persons and I have never worked on Windows specific stuff although it seems the Windows facilities are actually more flexible). Depending on the result of poll() (timeout or activity on the I/O device in that case) you'd do the appropriate action.
This problem is solvable in multiple ways (another idea that comes to mind is multithreading, but that seems overkill). One approach would be to keep track of the number of "game cycles" and execute some function every n-th cycle like this:
for(int32_t count{1};;count++)
{
if (!count % 5)
{
// do something every 5th cycle
}
// do something every cycle
sleep(x);
}
you can measure how much time has passed since last fall and move piece down after given amount and then reset counter. In pseudo-code it could look like this:
while(true)
{
counter.update();
if(counter.value() == fall_period)
{
move_piece_down();
couter.reset();
}
// rotate pieces
}
If you are using typical implementation of game loop your counter can just accumulate elapsed time since last frame.

Alarm Clock with multi alarms alghoritm C++

I've got a simple C++ task - I need to create an alarm app, which triggers alarms a few times.
For example, there is a text file with lines of time in format: hour minutes
I read these into an array.
My idea is that I create an infinite loop which checks what time is it every 60 seconds. Inside this loops, it checks if time == time_array_element_1 or time == time_array_element_2 etc.
And it check every 60 seconds.
Could you guys help me to decide, maybe there is some more optimal way to do it?
"optimal" strongly depends on what you want to achieve:
If you just want to have an alarm: use an existing app.
If you need to implement it on your own program, use a library that provides timer (e.g., Qt, boost, ...)
If you can't use 3rd party libraries because you're not allowed to (homework?): build your own.
If you don't want or cannot build your own timer library: use that loop approach.
If you want to run the alarm at a particular time every day, you could write an infinite loop that checks whether that time has come. Pseudo-Code:
const int alarm_time
const int sleep_time;
while (true) {
const int current = get_seconds_since_midnight();
if (current - alarm_time < sleep_time) {
alarm();
}
sleep(sleep_time);
}
However, you'd still need to keep this program running all the time.
That's fine if you just want to learn.
But for any other use-case, this task should be handled by the OS (e.g., cron on unix).

Why does time measurement sometimes return repetitive values (multiples of 15.625ms)?

I've done a lot of searching and found similar questions, but I still can't understand why sometimes my code gets the time right, and other times decides to become useless and return repetitive values.
A simple C++ code you can run to test this:
#include <iostream>
#include <chrono>
#include <windows.h>
//#include <unistd.h> //For Unix
void stall(int milisseconds){
auto start = std::chrono::high_resolution_clock::now();
Sleep(milisseconds);
//usleep(milisseconds*1000); //For Unix
auto finish = std::chrono::high_resolution_clock::now();
std::cout<<std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count()/1000000.0<<" ms\n";
}
int main(){
std::cout<<"Begin\n";
for (int i = 1; i < 100; i++){
stall(i);
}
}
Running this, the expected output would be something like:
1 ms
2 ms
3 ms
4 ms
...
98 ms
99 ms
100 ms
Sometimes it works, but other times (like, at random), the output looks like this:
15.625 ms
15.62 ms
15.632 ms
7.997 ms
16.713 ms
15.637 ms
31.25 ms
31.263 ms
31.245 ms
31.25 ms
21.985 ms
...
93.718 ms
93.77 ms
93.744 ms
102.263 ms
109.369 ms
96.192 ms
109.367 ms
109.368 ms
How can I eliminate this awful inconsistency? Reducing the number of background processes doesn't seem to have any effect.
I would guess this would be due to your OS' scheduling quantum: If your thread yields or finishes its execution time quantum, some other threads will run for that quantum, and then when your thread runs again, a full quantum (and a bit) has elapsed. So you see advances by noise + either 0 quanta or 1 quantum.
einpoklum suggested that it could be because of my OS' scheduling quantum, which sounds about right. I was about to go crazy, thinking that it was something beyond my control (or too complicated to solve), but I ended up somehow discovering a way of manipulating it in my favor. I noticed that, if the internet browser was closed, the times returned were a very consistent sequence of multiples of 15.625. But if I had the browser running, it looked like the more tabs I had opened, the more inconsistent the times where (but still leaning towards multiples of 15.625). And if a tab had something loading, the numbers started looking like a regular sequence of 1 to 1!
So, I concluded that whevener I had to do testing, I'd put a Youtube or Twitch tab by the side. It's weird as hell (if there's a better way to do it, I'd like to know), but for now, I will have to unite the useful with the pleasent, lol

C++ Timer control

I want to create a timer so that after completing the time(suppose 10 sec) the control should come out of the function..Please note that am starting the timer inside the function.Code is given below..I want to give certain time limit to that function so that after completing the time the control should come out of the function..I don't want to calculate the time..I want to give my own time so that the function should complete its execution within that time period..suppose if function is waiting for an input then also after completing time limit the control should come out indicating that "time has expired"..once it comes out of the function then it should continue with the next function execution...Is this possible in c++...
Begin();
// here I would like to add timer.
v_CallId = v_CallId1;
call_setup_ind();
call_alert_ind();
dir_read_search_cnf();
dir_save_cnf();
END();
If the code is linear and the functions called cannot be chopped into smaller pieces, your stuck to letting an external process/thread do the timing and abort the worker thread when the timeout is exceeded.
When you can chop the worker into smaller pieces you could do something like this
Timeout.Start(5000);
while ((TimeOut.TimeOut() == false) && (completed == false))
{
completed = WorkToDo()
}
This is a pattern we frequently use in our embbeded application. The timeout class was in house develop. It just reads the tick counter and looks if the time has passed. An framework like QT or MFC should have such a class itself.