Equivalent to window.setTimeout() for C++ - c++

In javascript there's this sweet, sweet function window.setTimeout( func, 1000 ) ; which will asynchronously invoke func after 1000 ms.
I want to do something similar in C++ (without multithreading), so I put together a sample loop like:
#include <stdio.h>
struct Callback
{
// The _time_ this function will be executed.
double execTime ;
// The function to execute after execTime has passed
void* func ;
} ;
// Sample function to execute
void go()
{
puts( "GO" ) ;
}
// Global program-wide sense of time
double time ;
int main()
{
// start the timer
time = 0 ;
// Make a sample callback
Callback c1 ;
c1.execTime = 10000 ;
c1.func = go ;
while( 1 )
{
// its time to execute it
if( time > c1.execTime )
{
c1.func ; // !! doesn't work!
}
time++;
}
}
How can I make something like this work?

After C++11 came out, and if your are using c++11 supported compiler, you can use lambda, variadic template function and asynchronous thread to simulate javascript function in c++ easily.
Here is the code I wrote for setTimeOut, it is fully tested:
setTimeOut funtion's definition:
#include <windows.h>//different header file in linux
#include <future>
using namespace std;
template <typename... ParamTypes>
void setTimeOut(int milliseconds,std::function<void(ParamTypes...)> func,ParamTypes... parames)
{
std::async(std::launch::async,[=]()
{
Sleep(milliseconds);
func(parames...);
});
};
This function accepts variable arguments by using c+11's variadic template,
The code can show you how to use it:
#include <iostream>
#include <thread>
#include <string>
#include <functional>
#include <windows.h>
#include <future>
using namespace std;
int main()
{
std::mutex locker;
std::function<void()> func1 = [&]()
{
std::unique_lock<std::mutex> lk(locker);
std::cout << "func 1 is trigged:" << " no parameter" << std::endl;
lk.unlock();
};
std::function<void(int)> func2 = [&](int param)
{
std::unique_lock<std::mutex> lk(locker);
std::cout << "func 2 is trigged:" << " int: " << param <<std::endl;
lk.unlock();
};
std::function<void(int,std::string)> func3 = [&](int param1,std::string param2)
{
std::unique_lock<std::mutex> lk(locker);
std::cout << "func 3 is trigged:" << " int: " << param1 << "; string: " << param2 << std::endl;
lk.unlock();
};
for(int index=0;index<100;index++)
{
std::unique_lock<std::mutex> lk1(locker);
std::cout << "set timer for func 1" << std::endl;
lk1.unlock();
setTimeOut<>(1000,func1);
std::unique_lock<std::mutex> lk2(locker);
std::cout << "set timer for func 2" << std::endl;
lk2.unlock();
setTimeOut<int>(2000,func2,10000);
std::unique_lock<std::mutex> lk3(locker);
std::cout << "set timer for func 3" << std::endl;
lk3.unlock();
setTimeOut<int,std::string>(5000,func3,10000,"ddddd");
}
Sleep(10000000);
}

Make Callback::func of type void (*)(), i.e.
struct Callback
{
double execTime;
void (*func)();
};
You can call the function this way:
c1.func();
Also, don't busy-wait. Use ualarm on Linux or CreateWaitableTimer on Windows.

In C++ by itself, you're pretty limited. You need either a multithreaded OS, where you could use a sleep function (you can still have the program continue running with a separate thread), or you need a messaging system, like Windows.
The only other way I see that you can do something is to have a lot of calls scattered throughout the code that calls a function that returns true or false, depending on whether the time has elapsed. The function could, of course, be a callback, but you would still need to call it periodically.

I'm only fixing your code here, not thinking outside the box. The other answers already gave some pointers for that.
For better type safety, you should declare your callback pointer as follows:
// The function to execute after execTime has passed
void (*func)() ;
Then, call it as:
c1.func() ;

Another (better) answer would be to use the <functional> header in C++, and declare the function like so:
#include <functional>
function<void ()> func ;
// assign like
func = go ; //go is a function name that accepts 0 parameters
// and has return type void
// exec like
func() ;

Related

C++: How to pass a function+arguments as parameter without executing it?

I have 3 algorithms function:
void algo1(int para1, int para2);
void algo2(int para1, int para2);
void algo3(int para1, int para2);
and I want set a timer to test these functions' efficiency
int get_execute_time( void(*f)(int para1, int para2) );
I pass the function as parameter to get_execute_time to avoid abundance, however, the problem is I also need to pass the arguments, which is para1, para2.
so I let timer function change to
get_execute_time( void(*f)(int para1, int para2) ,
int para1, int para2) {
(*f)(para1, para2); // call it
}
and, the code above seems ugly to me, so is there any option to wrap the code and let the code execute later in C++?
so that I can do like this:
// definition
get_execute_time(this_code_will_execute_later) {
this_code_will_execute_later();
};
// usage
get_execute_time(algo1(para1, para2));
Temporary solution: utilize class to implement closure-like thing( inspired from Do we have closures in C++?
class timer {
private:
int para1;
int para2;
public:
timer(int para1, int para2);
operator () (void(*f)(int para1, int para2)) { (*f)(para1, para2) }
}
// thus we can write these following code
timer timer(para1, para2);
std::cout << "run " << timer(algo1) << " ms";
std::cout << "run " << timer(algo2) << " ms"
std::cout << "run " << timer(algo3) << " ms"
So, Do exist better options? Thanks anyway!
You can do this with either std::bind or via a lambda. For example (just one parameter shown for brevity):
#include <iostream>
#include <functional>
void get_execute_time (std::function <void (void)> f)
{
f ();
}
void foo (int i)
{
std::cout << i << '\n';
}
int main()
{
int param = 42;
auto f1 = std::bind (foo, param);
get_execute_time (f1);
++param;
auto f2 = [param] { foo (param); };
get_execute_time (f2);
}
Output:
42
43
Live demo

Multiple threads passing parameter

Having:
class CPU() {};
void executable() {} , inside CPU; this function is executed by a thread.
void executable(){
while(run) { // for thread
cout << "Printing the memory:" << endl;
for (auto& t : map) {
cout << t.first << " " << t.second << "\n";
}
}
}
Need to instantiate 5 threads that execute executable() function:
for (int i = 0; i < 5; i++)
threads.push_back(thread(&CPU::executable, this)); //creating threads
cout << "Synchronizing all threads...\n";
for (auto& th : threads) th.join(); //waits for all of them to finish
Now, I want to create:
void executable0 () {
while(run) {
cout << "Printing the memory:" << endl;
for (auto& t : map) {
cout << t.first << " " << t.second << "\n";
}
}
}
void executable1 () {....}
to executable4() {....} // using that five threads that I`ve done above.
How could I do? Initialize or using std:thread constructor?
Can someone give me an example to understand this process.
Thanks & regards!
Following Some programmer dude's comment, I would also advise using a standard container of std::function:
#include <iostream>
#include <thread>
#include <map>
#include <functional>
#include <vector>
class CPU {
std::vector<std::function<void()>> executables{};
std::vector<std::thread> threads{};
public:
CPU() {
executables.emplace_back([](){
std::cout << "executable0\n";
});
executables.emplace_back([](){
std::cout << "executable1\n";
});
executables.emplace_back([](){
std::cout << "executable2\n";
});
}
void create_and_exec_threads() {
for(const auto executable : executables) {
threads.emplace_back([=](){ executable(); });
}
for(auto& thread : threads) {
thread.join();
}
}
};
We create a vector holding three callbacks, which will be used to initialise threads and start them inside create_and_exec_threads method.
Please do note that, as opposed to the comment in your example, creating a std::thread with a callback passed to its contructor will not only construct the thread, but also it will start it immediately.
Additionally, the std::thread::join method does not start the the thread. It waits for it to finish.

Are boost::bind and boost::function compatible with SEH?

I have a function that uses boost::bind to move function evaluation into a try/catch wrapper, based on this question.
Problem is, boost::bind doesn't seem to work with SEH - and worse, it returns a garbage value, which is exactly what I don't want. Have I made a botch of it somewhere? Even stranger, the switch /EHsc or /EHa doesn't actually seem to matter to the behavior of the program. The output you get is:
Calling
-2147483648
Done.
Press any key to continue . . .
How do I even start to figure out where things have gone wrong?
#pragma once
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <windows.h>
#include <eh.h>
using boost::function;
using boost::bind;
int potato(int q)
{
double r = 0;
return q / r;
}
template<typename T>
T exception_wrapper(boost::function<T()> func)
{
try
{
std::cout << "Calling" << std::endl;
return func();
std::cout << "After Call" << std::endl;
}
catch (...) {
std::cout << "Ex Caught" << std::endl;
return 45;
}
}
void trans_func(unsigned int u, EXCEPTION_POINTERS* pExp)
{
throw std::runtime_error("huh");
}
int main()
{
int result = exception_wrapper<int>(bind(potato, 123));
std::cout << result << std::endl;
std::cout << "Done." << std::endl;
}

Calling method that modifies a field while another method that uses that field is executing

I have a question regarding the outside modification of a running method.
Given this C++ class:
#include <iostream>
class Foo {
public:
Foo()
: runBar(true) {}
void bar() {
int i = 0;
while(this->runBar) {
std::cout << "Loop " << i++ << std::endl;
}
std::cout << "Loop done!" << std::endl;
}
void baz() {
this->runBar = false;
std::cout << "Field changed!" << std::endl;
}
private:
bool runBar;
};
And also given this main function:
int main(int argc, char* argv[]) {
Foo f;
f.bar();
f.baz();
return 0;
}
What happens when the call to Foo::baz() is made?
Thanks for the help!
Since you only have 1 thread of execution, and you do not have anything to change the while loop exit condition in the bar function, this code will loop forever. Your baz function will never be called.
Assuming you meant to call them from separate threads,
here is an example showing main modified to call the function from within a thread.
Foo is using a mutext to coordinate activity, like allowing the thread to finish printing before being terminated.
The join prevents termination of main from ending everything prematurely.
If you don't coordinate them in some way such as that, it would not possible to say with certainty what the sequence of events would be. Such is the nature of programming with multiple threads.
Either bar runs first in which case it prints, or else baz runs first in which case bar will not. Either is possible.
#include <iostream>
#include <mutex>
mutex aMutex; //<--
class Foo {
public:
Foo()
: runBar(true) {}
void bar() {
int i = 0;
while(this->runBar) {
aMutex.lock(); //<--
std::cout << "Loop " << i++ << std::endl;
aMutex.unlock(); //<--
}
std::cout << "Loop done!" << std::endl;
}
void baz() {
this->runBar = false;
aMutex.lock(); //<--
std::cout << "Field changed!" << std::endl;
aMutex.unlock(); //<--
}
private:
bool runBar;
};
#include <thread>
int main(int argc, char* argv[]) {
Foo f;
thread myThread { f.bar() }; //call it in a thread
f.baz();
myThread.join(); //<--
return 0;
}

Dynamically creating a C++ function argument list at runtime

I'm trying to generate an argument list for a function call during runtime, but I can't think of a way to accomplish this in c++.
This is for a helper library I'm writing. I'm taking input data from the client over a network and using that data to make a call to a function pointer that the user has set previously. The function takes a string(of tokens, akin to printf), and a varying amount of arguments. What I need is a way to add more arguments depending on what data has been received from the client.
I'm storing the functions in a map of function pointers
typedef void (*varying_args_fp)(string,...);
map<string,varying_args_fp> func_map;
An example usage would be
void printall(string tokens, ...)
{
va_list a_list;
va_start(a_list, tokens);
for each(auto x in tokens)
{
if (x == 'i')
{
cout << "Int: " << va_arg(a_list, int) << ' ';
}
else if(x == 'c')
{
cout << "Char: " << va_arg(a_list, char) << ' ';
}
}
va_end(a_list);
}
func_map["printall"] = printall;
func_map["printall"]("iic",5,10,'x');
// prints "Int: 5 Int: 10 Char: x"
This works nicely when hardcoding the function call and it's arguments, but if I've received the data "CreateX 10 20", the program needs to be able to make the argument call itself. eg
// func_name = "CreateX", tokens = 'ii', first_arg = 10, second_arg = 20
func_map[func_name](tokens,first_arg,second_arg);
I can't predict how users are going to lay out the functions and code this beforehand.
If anyone has suggestions on accomplishing this task another way, feel free to suggest. I need the user to be able to "bind" a function to the library, and for the library to call it later after it has received data from a networked client, a callback in essence.
Here is a C++11 solution. It does not support varargs functions like printall or printf, this is impossible with this technique and IMO impossible at all, or at the very least extremely tricky. Such function are difficult to use safely in an environment like yours anyway, since any bad request from any client could crash the server, with absolutely no recourse whatsoever. You probably should move to container-based interface for better safety and stability.
On the other hand, this method supports all (?) other functions uniformly.
#include <vector>
#include <iostream>
#include <functional>
#include <stdexcept>
#include <string>
#include <boost/any.hpp>
template <typename Ret, typename... Args>
Ret callfunc (std::function<Ret(Args...)> func, std::vector<boost::any> anyargs);
template <typename Ret>
Ret callfunc (std::function<Ret()> func, std::vector<boost::any> anyargs)
{
if (anyargs.size() > 0)
throw std::runtime_error("oops, argument list too long");
return func();
}
template <typename Ret, typename Arg0, typename... Args>
Ret callfunc (std::function<Ret(Arg0, Args...)> func, std::vector<boost::any> anyargs)
{
if (anyargs.size() == 0)
throw std::runtime_error("oops, argument list too short");
Arg0 arg0 = boost::any_cast<Arg0>(anyargs[0]);
anyargs.erase(anyargs.begin());
std::function<Ret(Args... args)> lambda =
([=](Args... args) -> Ret {
return func(arg0, args...);
});
return callfunc (lambda, anyargs);
}
template <typename Ret, typename... Args>
std::function<boost::any(std::vector<boost::any>)> adaptfunc (Ret (*func)(Args...)) {
std::function<Ret(Args...)> stdfunc = func;
std::function<boost::any(std::vector<boost::any>)> result =
([=](std::vector<boost::any> anyargs) -> boost::any {
return boost::any(callfunc(stdfunc, anyargs));
});
return result;
}
Basically you call adaptfunc(your_function), where your_function is a function of any type (except varargs). In return you get an std::function object that accepts a vector of boost::any and returns a boost::any. You put this object in your func_map, or do whatever else you want with them.
Types of the arguments and their number are checked at the time of actual call.
Functions returning void are not supported out of the box, because boost::any<void> is not supported. This can be dealt with easily by wrapping the return type in a simple template and specializing for void. I've left it out for clarity.
Here's a test driver:
int func1 (int a)
{
std::cout << "func1(" << a << ") = ";
return 33;
}
int func2 (double a, std::string b)
{
std::cout << "func2(" << a << ",\"" << b << "\") = ";
return 7;
}
int func3 (std::string a, double b)
{
std::cout << "func3(" << a << ",\"" << b << "\") = ";
return 7;
}
int func4 (int a, int b)
{
std::cout << "func4(" << a << "," << b << ") = ";
return a+b;
}
int main ()
{
std::vector<std::function<boost::any(std::vector<boost::any>)>> fcs = {
adaptfunc(func1), adaptfunc(func2), adaptfunc(func3), adaptfunc(func4) };
std::vector<std::vector<boost::any>> args =
{{777}, {66.6, std::string("yeah right")}, {std::string("whatever"), 0.123}, {3, 2}};
// correct calls will succeed
for (int i = 0; i < fcs.size(); ++i)
std::cout << boost::any_cast<int>(fcs[i](args[i])) << std::endl;
// incorrect calls will throw
for (int i = 0; i < fcs.size(); ++i)
try {
std::cout << boost::any_cast<int>(fcs[i](args[fcs.size()-1-i])) << std::endl;
} catch (std::exception& e) {
std::cout << "Could not call, got exception: " << e.what() << std::endl;
}
}
As already mentioned by #TonyTheLion, you can use boost::variant or boost::any to select between types at runtime:
typedef std::function<void(const std::string&, const std::vector<boost::variant<char, int>>&)> varying_args_fn;
std::map<std::string, varying_args_fn> func_map;
The you can e.g. use a static visitor to distinguish between the types. Here is a full example, note that the tokens parameter is actually no longer necessary since boost::variant knows at runtime what type is stored in it:
#include <map>
#include <vector>
#include <string>
#include <functional>
#include <iostream>
#include <boost/variant.hpp>
#include <boost/any.hpp>
typedef std::function<void(const std::string&, const std::vector<boost::variant<char, int>>&)> varying_args_fn;
void printall(const std::string& tokens, const std::vector<boost::variant<char, int>>& args) {
for (const auto& x : args) {
struct : boost::static_visitor<> {
void operator()(int i) {
std::cout << "Int: " << i << ' ';
}
void operator()(char c) {
std::cout << "Char: " << c << ' ';
}
} visitor;
boost::apply_visitor(visitor, x);
}
}
int main() {
std::map<std::string, varying_args_fn> func_map;
func_map["printall"] = printall;
func_map["printall"]("iic", {5, 10, 'x'});
}