I want to add a delay so that one line will run and then after a short delay the second one will run. I'm fairly new to C++ so I'm not sure how I would do this whatsoever. So ideally, in the code below it would print "Loading..." and wait at least 1-2 seconds and then print "Loading..." again. Currently it prints both instantaneously instead of waiting.
cout << "Loading..." << endl;
// The delay would be between these two lines.
cout << "Loading..." << endl;
in c++ 11 you can use this thread and crono to do it:
#include <chrono>
#include <thread>
...
using namespace std::chrono_literals;
...
std::this_thread::sleep_for(2s);
to simulate a 'work-in-progress report', you might consider:
// start thread to do some work
m_thread = std::thread( work, std::ref(*this));
// work-in-progress report
std::cout << "\n\n ... " << std::flush;
for (int i=0; i<10; ++i) // for 10 seconds
{
std::this_thread::sleep_for(1s); //
std::cout << (9-i) << '_' << std::flush; // count-down
}
m_work = false; // command thread to end
m_thread.join(); // wait for it to end
With output:
... 9_8_7_6_5_4_3_2_1_0_
work abandoned after 10,175,240 us
Overview: The method 'work' did not 'finish', but received the command to abandon operation and exit at timeout. (a successful test)
The code uses chrono and chrono_literals.
In windons OS
#include <windows.h>
Sleep( sometime_in_millisecs ); // note uppercase S
In Unix base OS
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
#include <unistd.h>
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals
You want the sleep(unsigned int seconds) function from unistd.h. Call this function between the cout statements.
Related
I have a program in which I want to call a function after x seconds or minutes while keep running rest of the program.
You should run new thread:
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
// The function we want to execute on the new thread.
void task(int sleep)
{
std::this_thread::sleep_for (std::chrono::seconds(sleep));
cout << "print after " << sleep << " seconds" << endl;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task, 5);
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
I have three issues with the attached code, which has to do with threading. I need to make function calls to provide information about the following three items:
Is the thread vecOfThreads[1] empty without any tasks currently running on it
Is the thread vecOfThreads[0] joinable() but not ready to be join()ed
This would be the else statement of 2). If a thread is joinable() and won't wait to join() then go ahead and join()
#include <iostream>
#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
#include <vector>
void f1();
void f1() {
std::this_thread::sleep_for(std::chrono::seconds {3});
std::cout << "DONE SLEEPING!" << std::endl;
}
int main() {
int processor_count = 2; // consider that this CPU has two processors
std::vector<std::thread> vecOfThreads(processor_count);
std::thread t1(f1);
vecOfThreads[0] = std::move(t1);
if (vecOfThreads[0].joinable()) { // how to check to see if vecOfThreads[1] would be good to start a process on?
std::cout << "this is joinable, but not yet ready to be joined \n";
std::cout << "How to know: \n \t 1) if the thread is not being used "
"\n \t 2) if the thread is in use, but not yet ready to be `join()`ed \n \t "
"3) if the thread is both joinable and will not wait for a join()" << std::endl;
vecOfThreads[0].join();
}
return 0;
}
Compile with
g++ -std=c++17 -pthread
I would like to be able to submit say 12 tasks, but I only have 2 threads available. I want for a new task to be submitted right away when one of the threads finish. Is this possible?
Thank you for your time.
I'm trying to write a kind of thread pool in C++. The code works fine in OSX, but under Linux I'm experiencing a strange behavior.
After a bit of debugging, I found the problem is due to a call to std::condition_variable::wait_until that I must be doing in a wrong way.
With the code below I expect the loop to be looped once every three seconds:
#include <mutex>
#include <chrono>
#include <iostream>
#include <memory>
#include <condition_variable>
#include <thread>
using namespace std;
typedef std::chrono::steady_clock my_clock;
typedef std::chrono::duration<float, std::ratio<1> > seconds_duration;
typedef std::chrono::time_point<my_clock, seconds_duration> timepoint;
timepoint my_begin = my_clock::now();
float timepointToFloat(timepoint time) {
return time.time_since_epoch().count() - my_begin.time_since_epoch().count();
}
void printNow(std::string mess) {
timepoint now = my_clock::now();
cout << timepointToFloat(now) << " " << mess << endl;;
};
void printNow(std::string mess, timepoint time ) {
timepoint now = my_clock::now();
cout << timepointToFloat(now) << " " << mess << " " << timepointToFloat(time) << endl;;
};
int main() {
mutex _global_mutex;
condition_variable _awake_global_execution;
auto check_predicate = [](){
cout << "predicate called" << endl;
return false;
};
while (true) {
{ // Expected to loop every three seconds
unique_lock<mutex> lock(_global_mutex);
timepoint planned_awake = my_clock::now() + seconds_duration(3);
printNow("wait until", planned_awake);
_awake_global_execution.wait_until(lock, planned_awake, check_predicate);
}
printNow("finish wait, looping");
}
return 0;
}
However, sometimes I get as output:
<X> wait until <X+3>
predicate called
(...hangs here for a long time)
(where X is a number), so it seems the timeout is not scheduled after three seconds. Sometimes instead I get:
<X> wait until <X+3>
predicate called
predicate called
<X> finish wait, looping
<X> wait until <X+3> (another loop)
predicate called
predicate called
<X> finish wait, looping
(...continue looping without waiting)
so it seems the timeout is scheduled after a small fraction of seconds. I think I'm messing up something with the timeout timepoint, but I cannot figure out what I'm doing wrong.
If it may be relevant, this code works fine in OSX, while in Linux (Ubuntu 16.04, gcc 5.4, compiled with "g++ main.cc -std=c++11 -pthread") I'm experiencing the strange behavior.
How can I get it work?
Try to cast your timeout to your clock's duration:
auto planned_awake = my_clock::now() +
std::chrono::duration_cast<my_clock::duration>(seconds_duration(3));
I've recently tried cpp, in the thing I'm making I'm trying to make it so that a variable with the value of 20 is subtracted by 1 every second, but I also need the machine to be waiting for an input from the user. I tried using for loops but they won't proceed until the input is placed or until the variable runs out. I looked at clock but they don't seem to fit my need, or maybe I just misunderstood their purpose.
Any suggestions?
As has already been suggested in the comments, threading is one way to do this. There is a nice self-contained example here (which I've borrowed from in the code below).
In the code below an asynchronous function is launched. Details on these here. This returns a future object which will contain the result once the job has finished.
In this case the job is listening to cin (typically the terminal input) and will return when some data is entered (i.e. when enter is pressed).
In the meantime the while loop will be running which keeps a track of how much time has passed, decrements the counter, and also returns if the asynchronous job finishes. It wasn't clear from your question if this is exactly the behaviour you want but it gives you the idea. It will print out value of decremented variable, but user can enter text, and it will print that out once user presses enter.
#include <iostream>
#include <thread>
#include <future>
#include <time.h>
int main() {
// Enable standard literals as 2s and ""s.
using namespace std::literals;
// Execute lambda asyncronously (waiting for user input)
auto f = std::async(std::launch::async, [] {
auto s = ""s;
if (std::cin >> s) return s;
});
// Continue execution in main thread, run countdown and timer:
int countdown = 20;
int countdownPrev = 0;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end;
double elapsed;
while((f.wait_for(5ms) != std::future_status::ready) && countdown >= 0) {
end = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();
countdown = 20 - (int) (elapsed/1000);
if (countdown != countdownPrev) {
std::cout << "Counter now: " << std::fixed << countdown << std::endl;
countdownPrev = countdown;
}
}
if (countdown == -1) {
std::cout << "Countdown elapsed" << std::endl;
return -1;
} else {
std::cout << "Input was: " << f.get() << std::endl;
return 0;
}
}
P.S. to get this to work on my compiler I have to compile it with g++ -pthread -std=c++14 file_name.cpp to correctly link the threading library and allow use of c++14 features.
void sendCommand(float t,char* cmd)
{
std::clock_t endwait;
double endwait = clock () + t * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
if( clock() < endwait)
printf("\nThe waited command is =%s",cmd);
}
void Main()
{
sendCommand(3.0,"Command1");
sendCommand(2.0,"Command2");
printf("\nThe first value")
return 0;
}
i want to delay a function but my application should keep on running.
In the above code i want The first value to be printed first.
than i want Command2 to be printed and Command1 should be the last to be printed.
I prefer std::async for this.
#include <chrono>
#include <thread>
#include <future>
#include <iostream>
void sendCommand(std::chrono::seconds delay, std::string cmd)
{
std::this_thread::sleep_for( delay );
std::cout << "\nThe waited command is =" << cmd;
}
int main()
{
auto s1 = std::async(std::launch::async, sendCommand, std::chrono::seconds(3),"Command1");
auto s2 = std::async(std::launch::async, sendCommand, std::chrono::seconds(2),"Command2");
std::cout << "\nThe first value" << std::flush;
s1.wait();
s2.wait();
return 0;
}
However, for a real design, I would create a scheduler (or preferably use an existing one) which manages a priority queue sorted by the delay time. Spawning a new thread for every command will quickly become a problem. Since you flagged the question for MS VIsual C++, take a look the PPL which implements task-based parallelism.
And as it a C++ question, I would stay away from the C stuff and not use printf, CLOCK_PER_SEC, char*, clock etc. You will quickly get into problems even with this simple example when you start using strings instead of the "Command1" literals. std::string will help you here.
I think you need threads. You can do it like this:
#include <thread>
#include <chrono>
#include <iostream>
void sendCommand(float t, char const* cmd)
{
std::this_thread::sleep_for(std::chrono::milliseconds(int(t * 1000)));
std::cout << "\nThe waited command is = " << cmd << '\n';
}
int main()
{
// each function call on a new thread
std::thread t1(sendCommand, 3.0, "Command1");
std::thread t2(sendCommand, 2.0, "Command2");
// join the threads so we don't exit before they finish.
t1.join();
t2.join();
}
You can do it in many ways depending upon your actual logic.
Examles;:
1.you can you a global flag variable and check its state , when third print will complete you can set flag to 1,so next call will execute.
2.you can use a STACK .push all the function pointers in a STACK . and after that pop and execute.
3.MultiThreading. You can use it with proper synchronized way, but it will be complex. It depends upon your requirement.
Thanks !!!
boost::asio is nice because it doesn't require the overhead of multiple threads.
#include <iostream>
#include <boost/asio.hpp>
using namespace std;
int main()
{
boost::asio::io_service svc;
boost::asio::deadline_timer t0{svc};
boost::asio::deadline_timer t1{svc};
boost::asio::deadline_timer t2{svc};
t0.expires_from_now(boost::posix_time::seconds{1});
t1.expires_from_now(boost::posix_time::seconds{2});
t2.expires_from_now(boost::posix_time::seconds{3});
t2.async_wait([] (const boost::system::error_code& ec) { if(!ec) std::cout << "Greetings from t2!\n";});
t1.async_wait([] (const boost::system::error_code& ec) { if(!ec) std::cout << "Greetings from t1!\n";});
t0.async_wait([] (const boost::system::error_code& ec) { if(!ec) std::cout << "Greetings from t0!\n";});
svc.post([] () { std::cout << "I'm number one!\n";});
svc.run();
return 0;
}
Gives the output:
I'm number one!
Greetings from t0!
Greetings from t1!
Greetings from t2!