C++ background timer - c++

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
using namespace System;
void wait ( int seconds )
{
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
void timer()
{
int n;
printf ("Start\n");
for (n=10; n>0; n--) // n = time
{
cout << n << endl;
wait (1); // interval (in seconds).
}
printf ("DONE.\n");
system("PAUSE");
}
int main ()
{
timer();
cout << "test" << endl; // run rest of code here.}
return 0;
}
I'm trying to create a timer in C++ which would run in the background. So basically if you'd look at the 'main block' I want to run the timer (which is going to count down to 0) and at the same time run the next code, which in this case is 'test'.
As it is now the next line of code won't be run until the timer has finished. How do I make the timer run in the background?
Thanks for your help in advance!

C++11. Should work with VS11 beta.
#include <chrono>
#include <iostream>
#include <future>
void timer() {
std::cout << "Start\n";
for(int i=0;i<10;++i)
{
std::cout << (10-i) << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "DONE\n";
}
int main ()
{
auto future = std::async(timer);
std::cout << "test\n";
}
If the operation performed in timer() takes significant time you can get better accuracy like this:
void timer() {
std::cout << "Start\n";
auto start = std::chrono::high_resolution_clock::now();
for(int i=0;i<10;++i)
{
std::cout << (10-i) << '\n';
std::this_thread::sleep_until(start + (i+1)*std::chrono::seconds(1));
}
std::cout << "DONE\n";
}

Related

A timer that adds a second when it is paused

This should be a normal timer that runs until it's either paused or exited. The code is exited by the NextStep() Function. And The timer is supposed to pause and stay paused until it's pressed again.
However, when I press the spacebar, the timer stops only after adding another digit to the timer.
An example of the problem:
01sec
02sec
I press the spacebar.
03sec (+1sec)
The timer pauses.
On the other hand, the code that executes the NextStep() works fine without any delays.
I tried rewriting it in different ways, but none of them worked.
#pragma once
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <stdlib.h>
#include <iomanip>
#include <math.h>
#include <windows.h>
#include <conio.h>
#include <thread>
using namespace std;
void NextStep();
bool pause = false;
bool stop = false;
void wait(int milliseconds)
{
int counter = 0;
while (pause) {
char ch = _getch();
if (ch == ' ')
{
pause = !pause;
}
else if (ch == 27)
{
cout << "\033c";
NextStep();
stop = true;
}
}
while (counter < milliseconds && !stop)
{
if (pause) {
continue;
}
if (pause == false) {
this_thread::sleep_for(chrono::milliseconds(1));
counter++;
}
}
}
void timer()
{
int seconds = 0;
int minutes = 0;
int hours = 0;
while (true)
{
cout << "\033c";
cout << setfill(' ') << setw(55) << " Timer \n";
cout << " ";
cout << setfill('0') << setw(2) << hours << "h ";
cout << setfill('0') << setw(2) << minutes << "min ";
cout << setfill('0') << setw(2) << seconds << "sec ";
wait(60);
seconds++;
if (seconds == 60) {
minutes++;
seconds = 0;
}
else if (minutes == 60)
{
hours++;
minutes = 0;
seconds = 0;
}
if (_kbhit())
{
char ch = _getch();
if (ch == ' ')
{
pause = !pause;
}
else if (ch == 27)
{
cout << "\033c";
NextStep();
stop = true;
break;
}
}
}
}
Here's the NextStep() function:
void NextStep()
{
string option;
correct = false;
cout << "\033c";
cout << "Loading...";
Sleep(1300);
cout << "\033c";
cout << "What would you like to do next?" << endl;
cout << "" << endl;
cout << "To change your password TYPE: password" << endl;
cout << "To use a calculator TYPE: calculator" << endl;
cout << "To use a timer TYPE: timer" << endl;
cout << "" << endl;
cout << "Type your choice: ";
UserInput();
}
I'm not sure I understand all the workings of your code, but I think I understand that you need to have a timer that can be started, paused, and restarted. Also if I understood correctly the timer should not be affected (= paused) by the fact that the thread is in sleep.
So, here is an implementation of such a timer that might help you (at least for part of your problem) :
#include <chrono>
template<typename T>
class Timer
{
public:
void start()
{
m_start = std::chrono::steady_clock::now();
}
void pause()
{
m_elapsed += get_current_elapsed();
m_start = {};
}
void reset()
{
m_start = {};
m_elapsed = {};
}
int64_t get_elapsed()
{
return (m_elapsed + get_current_elapsed()).count();
}
private:
std::chrono::time_point<std::chrono::steady_clock> m_start{};
T m_elapsed{};
bool is_started()
{
return m_start.time_since_epoch() != T{};
}
T get_current_elapsed()
{
return is_started() ? std::chrono::duration_cast<T>(std::chrono::steady_clock::now() - m_start) : T{};
}
};
And here is an example of how it can be used :
#include <iostream>
#include <thread>
int main()
{
Timer<std::chrono::seconds> timer;
timer.start();
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.pause(); // "optional"
std::cout << timer.get_elapsed() << std::endl; // 1
timer.start(); // "optional"
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.pause(); // "optional"
std::cout << timer.get_elapsed() << std::endl; // 2
timer.reset();
timer.start();
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.pause(); // "optional"
std::cout << timer.get_elapsed() << std::endl; // 1
return 0;
}
Timer is a template, so instead of std::chrono::seconds you can use any of the following types depending on the precision you want for the timer :
std::chrono::nanoseconds
std::chrono::microseconds
std::chrono::milliseconds
std::chrono::seconds
std::chrono::minutes
std::chrono::hours
std::chrono::days
std::chrono::years

looping in background while running other statements c++

I want to make a program which displays current time that ticks in background then is it possible to initialize cin input processes while it is ticking?
just for fun:
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include <mutex>
#include <ctime>
std::mutex more_lock;
std::string more_output;
void set_more_output(const std::string& more)
{
std::lock_guard<std::mutex> lock(more_lock);
more_output = more;
}
std::string get_more_output()
{
std::lock_guard<std::mutex> lock(more_lock);
return more_output;
}
std::atomic_bool running {true};
std::thread start_timer_runner()
{
return std::thread([&]{
while(running) {
using namespace std::chrono;
using namespace std::chrono_literals;
auto now = system_clock::to_time_t(system_clock::now());
auto now_str = std::string(std::ctime(&now));
now_str.pop_back(); // ctime adds new line
std::cout << "\r" << now_str << " | " << get_more_output() << std::flush;
std::this_thread::sleep_for(1s);
}
});
}
void parse_decimals()
{
int x;
set_more_output("please enter a decimal: ");
while(std::cin >> x)
{
set_more_output("thanks! you entered " + std::to_string(x) + ", please enter a new decimal: ");
}
}
int main()
{
auto timer = start_timer_runner();
parse_decimals();
running = false;
timer.join();
std::cout << std::endl << "bye bye!" << std::endl;
}

how to use argument inside of thread? (C++)

i can't use delay argument inside of thread t
void HelloWorldDelay(int Delay)
{
cout << "Hello World";
atomic<bool> abort(false);
thread t([&abort]() {
Sleep(Delay);
abort = true;
});
t.join();
cout << Delay << "Ms ";
}
how to use it inside of thread t?
Sleep(Delay)
void HelloWorldDelay(int Delay) {
std::cout << "Hello World";
std::atomic<bool> abort(false);
std::thread t([&]() {
std::this_thread::sleep_for(std::chrono::seconds(Delay));
abort = true;
});
t.join();
std::cout << Delay << "Ms ";
}
will do the capturing
I think you should invoke like this :
#include <iostream>
#include <fstream>
#include <thread>
#include <atomic>
using namespace std;
void HelloWorldDelay(int Delay)
{
cout << "Hello World";
atomic<bool> abort(false);
thread t([&abort](int delay) {
//sleep(Delay);
std::this_thread::sleep_for(std::chrono::milliseconds(delay));
abort = true;
}, std::ref(Delay));
t.join();
cout << Delay << "Ms ";
}
int main()
{
HelloWorldDelay(3);
std::system("pause");
return 0;
}

How can I create a Barrier in c++?

I have 4-threads in my program. I want to execute all of them once and once all of them are executed then only I want to enter the next iteration of execution.
I got a code on stack overflow that implements the boost::barrier function in C++. But it does not seem to work for me. For one iteration it works fine. But for the next iteration, the program execution just hangs.
//Here is my top code:
#include <iostream>
#include <stdio.h>
#include <thread>
#include "abc_func.hpp"
#include <vector>
using namespace std;
int main() {
abc obj1;
obj1.num_threads(4);
std::thread t1([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_write(1));
};
});
std::thread t2([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_read(2));
};
});
std::thread t3([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_write(3));
};
});
std::thread t4([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_read(4));
};
});
t1.join();
t2.join();
t3.join();
t4.join();
// cout << "done: " << obj1.done << endl;
// cout << "done: " << obj2.done << endl;
// cout << "wr_count: " << obj1.wr_count << endl;
return 0;
}
// Here is the abc_func.hpp
#include <iostream>
#include <stdio.h>
#include <thread>
#include <barrier.hpp>
using namespace std;
class abc {
size_t n_threads;
public:
abc() : n_threads(0) {};
void num_threads (size_t l) {
n_threads = l;
}
Barrier task_bar{n_threads};
bool abc_write (auto id) {
thread_local int wr_count = 0;
if (wr_count == 1) {
std::cout << "write thread waiting" << id << endl;
task_bar.Wait();
wr_count = 0;
};
std::cout << "write thread running " << id << endl;
++wr_count;
return true;
}
bool abc_read (auto id) {
thread_local int rd_count=0;
if (rd_count == 1) {
std::cout << "read thread waiting" << id << endl;
task_bar.Wait();
rd_count = 0;
};
std::cout << "read thread running " << id << endl;
++rd_count;
return true;
}
};
// and the barrier class code which I got on stack overflow
#include <thread>
#include <condition_variable>
#include <mutex>
#include <iostream>
#include <stdio.h>
class Barrier {
public:
explicit Barrier(std::size_t iCount) :
mThreshold(iCount),
mCount(iCount),
mGeneration(0) {
}
void Wait() {
std::unique_lock<std::mutex> lLock{mMutex};
auto lGen = mGeneration;
if (!--mCount) {
mGeneration++;
mCount = mThreshold;
mCond.notify_all();
} else {
mCond.wait(lLock, [this, lGen] { return lGen != mGeneration; });
}
}
private:
std::mutex mMutex;
std::condition_variable mCond;
std::size_t mThreshold;
std::size_t mCount;
std::size_t mGeneration;
};
The problem with this code is the member
Barrier task_bar{n_threads};
It is initialized once at the beginning while n_threads is 0. Later, when you call
obj1.num_threads(4);
the barrier object is not updated.
When you update the barrier as well, it works as expected
class Barrier {
public:
// ...
void num_threads(size_t n) {
mThreshold = n;
mCount = n;
}
// ...
};
and in abc::num_threads()
void num_threads (size_t l) {
n_threads = l;
task_bar.num_threads(l);
}

std::async uses same thread and my code does not achieve parallelism.

I am using C++11 on Mac OS Xcode 4.3.2
std::async uses same thread and my code does not achieve parallelism. In sample code below I want to create 10 new threads. In each thread I want to calculate square root of input variable and set the result in promise. in main function I want to display the results calculated from threads. I am calling std::async with policy launch::async, So I expect it to create a new thread(10 times).
#include <mutex>
#include <future>
#include <thread>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
mutex iomutex;
void foo(int i, promise<double> &&prms)
{
this_thread::sleep_for(chrono::seconds(2));
prms.set_value(sqrt(i));
{
lock_guard<mutex> lg(iomutex);
cout << endl << "thread index=> " << i << ", id=> "<< this_thread::get_id();
}
}
int main()
{
{
lock_guard<mutex> lg(iomutex);
cout << endl << "main thread id=>"<< this_thread::get_id();
}
vector<future<double>> futureVec;
vector<promise<double>> prmsVec;
for (int i = 0; i < 10; ++i) {
promise<double> prms;
future<double> ftr = prms.get_future();
futureVec.push_back(move(ftr));
prmsVec.push_back(move(prms));
async(launch::async, foo, i, move(prmsVec[i]));
}
for (auto iter = futureVec.begin(); iter != futureVec.end(); ++iter) {
cout << endl << iter->get();
}
cout << endl << "done";
return 0;
}
However if I use std::thread, then I can achieve parallelism.
#include <mutex>
#include <future>
#include <thread>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
mutex iomutex;
void foo(int i, promise<double> &&prms)
{
this_thread::sleep_for(chrono::seconds(2));
prms.set_value(sqrt(i));
{
lock_guard<mutex> lg(iomutex);
cout << endl << "thread index=> " << i << ", id=> "<< this_thread::get_id();
}
}
int main()
{
{
lock_guard<mutex> lg(iomutex);
cout << endl << "main thread id=>"<< this_thread::get_id();
}
vector<future<double>> futureVec;
vector<promise<double>> prmsVec;
vector<thread> thrdVec;
for (int i = 0; i < 10; ++i) {
promise<double> prms;
future<double> ftr = prms.get_future();
futureVec.push_back(move(ftr));
prmsVec.push_back(move(prms));
thread th(foo, i, move(prmsVec[i]));
thrdVec.push_back(move(th));
}
for (auto iter = futureVec.begin(); iter != futureVec.end(); ++iter) {
cout << endl << iter->get();
}
for (int i = 0; i < 10; ++i) {
thrdVec[i].join();
}
cout << endl << "done";
return 0;
}
async(launch::async, foo, i, move(prmsVec[i]));
This line returns a future but because you do not assign it to anything the future's destructor runs at the end of the statement, which blocks and waits for the result by calling std::future::wait()
Why are you manually calling std::async with a promise, when it returns a future anyway? The point of async is that you don't need to manually use a promise, that's done internally for you.
Rewrite your foo() to return double then call it with async
#include <mutex>
#include <future>
#include <thread>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
mutex iomutex;
double foo(int i)
{
this_thread::sleep_for(chrono::seconds(2));
lock_guard<mutex> lg(iomutex);
cout << "\nthread index=> " << i << ", id=> "<< this_thread::get_id();
return sqrt(i);
}
int main()
{
cout << "\nmain thread id=>" << this_thread::get_id();
vector<future<double>> futureVec;
for (int i = 0; i < 10; ++i)
futureVec.push_back(async(launch::async, foo, i));
for (auto& fut : futureVec)
{
auto x = fut.get();
lock_guard<mutex> lg(iomutex);
cout << endl << x;
}
cout << "\ndone\n";
}