I need to keep track of an interval of time and call a function each time the interval has passed. I've consulted SDL's documentation on SDL_AddTimer, but gcc is complaining that I'm doing it wrong.
So, how can I make regular intervals, or how do I use AddTimer?
The examples for AddTimer in the SDL docs weren't clear to me. gcc has told me that I'm missing arguments in my callback function and that my timer doesn't exist in the scope (but I don't know what to declare). Here's what I've crappily tried:
SDL_AddTimer(3000,changeMusic,NULL);
Uint32 changeMusic(Uint32 interval, void *param){...
I thought maybe if the time elapsed was divisible by 3 seconds, then the function would run, but this ended up activating at an erratic frequency.
if(interval.getTicks()%3000==0){
changeMusic();
}
Or, if a countdown hit zero, reset it and call a function, but I don't know how to make a timer that counts down.
//something like this
cdTimer=(3000 to 0)
if(cdTimer==0){
cdTimer=(3000 to 0);
changeMusic();
}
I'm pretty sure, from your snippet, that you didn't declare the function before the call to SDL_AddTimer(), and thus the compiler thinks it's the wrong function parameters.
There are two solutions:
Move the callback function from the SDL_AddTimer() to somewhere before the timer call.
Use a forward declaration to move the function up.
It's also possible that you are trying to use a member function in a class, in which case it would have to be a static member function. Something like this:
class Mylene
{
public:
... // other stuff goes here ...
static Uint32 ChangeMusic(Uint32 x, void *p)
{
Mylene *self = reinterpret_cast<Mylene *>(p);
self->doChangeMusic();
return 0;
}
... more stuff here, perhaps ...
};
Mylene mylene(...); // Note, must not go out of scope before the ChangeMusic is called.
// ... stuff ...
timer_id = SDL_AddTimer(3000, &Mylene::ChangeMusic, &mylene); // Passing the mylene object...
... Do other things here for some time ...
Related
I have a timer class I use to time blocks of code. Essentially something like this:
timer.start();
////do something
timer.end();
I am looking for a compile-time way to ensure that both the start and end call exist, and are within scope. Even hacky methods.
Here is one example of what I mean...this would generate a compile-time error if "end()" is called, but not "start()", due to the way a hidden variable "foo" is initialized.
#define start_macro bool foo = false; timer.start();
#define end_macro foo = true; timer.end();
//start_macro
////do something
end_macro //generates error because start_macro not called, thus foo not declared
But obviously the application of that method is limited because it generates no error if end() is the function not called.
Are there any clever ways I can ensure both functions are called, in order and in scope, at compile-time? I'm not interested in any run-time checking methods...I'd like a faster way to catch missing calls.
Unfortunaley there is no general solution. You would need to tell the compiler somehow, what are the matching functions. And, you never know, in which scope the closing function should be. So, rather difficult to impossible.
The better approach would be to use a wrapper class with constructor/destructor solution. The constructor would start the timer and the destrcutor would stop it. But that is runtime . . .
Another solution would be to write macro, which injects the code between timer start and stop, between such statements. But really not nice and anyway, marcros are not recommended. There could be also a template approach, trying to mimick that.
But for this to judge you need to specify more requirements.
You can use RAII, define a class wrapper, for example ScopedTimer, it's constructor calls start() and the destructor calls end(). Make your Timer::start() and Timer::end() protected, and make ScopedTimer as a friend of Timer, so that only ScopedTimer can calls to them.
There is no runtime checking. And there is no compile time checking either. It just makes it impossible to write code that calls one of the functions but not the other.
class ScopedTimer {
public:
explicit ScopedTimer(Timer *tm)
: tm_(tm) {
this->tm_->start();
}
~ScopedTimer() { this->tm_->stop(); }
protected:
Timer* tm;
};
// Your code will be like this:
{ // This pair of braces defines the scope that you want to measure.
ScopedTimer st(&timer);
////do something
}
Just as Shawn pointed out in his comment. To make sure timer has started, you simple put start of timer in constructor and stop in destructor. I used this method while making measurements for my project.
class Timer {
public:
Clock clock;
Timer() { clock.start(); }
~Timer()
{
clock.stop();
saveMeasurements();
}
private:
void saveMeasurements(); //save measurements to file
}
I have a class called MatrixAlt and i'm trying to multi thread a function to do some work on that matrix.
My general method worked when I just implemented it in a couple of functions. But when I try to bring it into the class methods, I get an error.
The problematic line (or where it highlights anyway) is 4 lines from the end and the error message is in the comments just above it.
#include <vector>
#include <future>
#include <thread>
class MatrixAlt
{
public:
MatrixAlt();
// initilaise the matrix to constant value for each entry
void function01(size_t maxThreads);
void function02(size_t threadIndex);
};
MatrixAlt::MatrixAlt()
{
}
void MatrixAlt::function02(size_t threadIndex)
{
// do some stuff
return;
}
void MatrixAlt::function01(size_t maxThreads)
{
// To control async threads and their results
std::vector<std::future<bool>> threadsIssued;
// now loop through all the threads and orchestrate the work to be done
for (size_t threadIndex = 0; threadIndex < maxThreads; ++threadIndex)
{
// line 42 gives error:
// 'MatrixAlt::function02': non-standard syntax; use '&' to create a pointer to member
// 'std::async': no matching overloaded function found
threadsIssued.push_back(std::async(function02, threadIndex));
}
return;
}
Your first problem is solved like this
threadsIssued.push_back(std::async(&MatrixAlt::function02, this, threadIndex));
You need to specify the exact class::function and take its address and which instance of the class your doing it for, and then the parameters.
The second problem which you haven't see yet is this line
std::vector<std::future<bool>> threadsIssued;
All those futures will be lost in scope exit, like tears in rain. Time to destroy.
Freely after Blade runner.
All those moments will be lost in time, like tears in rain. Time to
die.
Whenever you have a member function in C++, that function takes the object itself as an implicit first argument. So you need to pass the object as well, but even then, it can't be called with the same syntax as a normal function that takes the object.
The simplest way to setup an asynchronous job in C++ is typically just to use lambdas. They've very clear and explicit. So, for example, you could change your call to:
threadsIssued.push_back(std::async([this] (size_t t) { this->function02(t);}, threadIndex));
This lambda is explicitly capturing the this pointer, which tells us that all of the function02 calls will be called on the same object that the calling function01 is called on.
In addition to being correct, and explicit, this also helps highlight an important point: all of the function02 objects will be running with mutable access to the same MatrixAlt object. This is very dangerous, so you need to make sure that function02 is thread safe, one way or another (usually easy if its conceptually const, otherwise perhaps need a mutex, or something else).
Having read a bit about function pointers and callbacks, I fail to understand the basic purpose of it. To me it just looks like instead of calling the function directly we use the pointer to that function to invoke it. Can anybody please explain me callbacks and function pointers? How come the callback takes place when we use function pointers, because it seems we just call a function through a pointer to it instead of calling directly?
Thanks
ps: There have been some questions asked here regarding callbacks and function pointers but they do not sufficiently explain my problem.
What is a Callbak function?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a operation(function) can take long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.
An practical example:
Windows event processing:
virtually all windows programs set up an event loop, that makes the program respond to particular events (eg button presses, selecting a check box, window getting focus) by calling a function. The handy thing is that the programmer can specify what function gets called when (say) a particular button is pressed, even though it is not possible to specify when the button will be pressed. The function that is called is referred to as a callback.
An source Code Illustration:
//warning: Mind compiled code, intended to illustrate the mechanism
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end()) // if a callback is registered for event
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
The above would output the following:
Cat
Dog
Cat
Bird
Cat
Hope this helps!
Note: This is from one of my previous answers, here
One very striking reason for why we need function pointers is that they allow us to call a function that the author of the calling code (that's us) does not know! A call-back is a classic example; the author of qsort() doesn't know or care about how you compare elements, she just writes the generic algorithm, and it's up to you to provide the comparison function.
But for another important, widely used scenario, think about dynamic loading of libraries - by this I mean loading at run time. When you write your program, you have no idea which functions exist in some run-time loaded library. You might read a text string from the user input and then open a user-specified library and execute a user-specified function! The only way you could refer to such function is via a pointer.
Here's a simple example; I hope it convinces you that you could not do away with the pointers!
typedef int (*myfp)(); // function pointer type
const char * libname = get_library_name_from_user();
const char * funname = get_function_name_from_user();
void * libhandle = dlopen(libname, RTLD_NOW); // load the library
myfp fun = (myfp) dlsym(libhandle, funname); // get our mystery function...
const int result = myfp(); // ... and call the function
// -- we have no idea which one!
printf("Your function \"%s:%s\" returns %i.\n", libname, funname, result);
It's for decoupling. Look at sqlite3_exec() - it accepts a callback pointer that is invoked for each row retrieved. SQLite doesn't care of what your callback does, it only needs to know how to call it.
Now you don't need to recompile SQLite each time your callback changes. You may have SQLite compiled once and then just recompile your code and either relink statically or just restart and relink dynamically.
It also avoids name collision. If you have 2 libs, both do sorting and both expect you to define a function called sort_criteria that they can call, how would you sort 2 different objects types with the same function?
It would quickly get complicated following all the if's and switches in the sort_criteria function, with callbacks you can specify your own function (with their nice to interpret name) to those sort functions.
I'm making a GUI API (for games, not an OS) and would like to implement animated buttons. I'd like to be able to create timed events, but, within the class.
example:
class TextBox
{
void changeColor(int color);
void createTimedEvent(func* or something, int ticks);
void animate()
{
createTimedEvent(changeColor(red),30);
}
};
So in this example, the timer would call the class instance's changeColor function, with argument red, after 30 ms. Is there a way to do this?
Basically, a function to call a function, which could be a function from a instancable class, wit n arguments, after a given interval has expired.
The precision of the timer is not a big deal for me.
Thanks
I believe you could make this work portably using Boost.Asio - this is primarily designed for async I/O but I see no reason why the timer code cannot be used in other contexts. See this example for how to kick off a timer which calls back your code after expiry.
The only proviso I noticed is that you have to call ioservice::run in some thread with the ioservice instance you used here, or the callbacks will not happen.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!\n";
}
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
t.async_wait(print);
// ensure we call io.run() from some thread or callbacks will not happen
// other app logic
return(0);
}
There is also a discussion of this very topic on MSDN blogs here by the author of the library.
I'd welcome anybody showing otherwise, but as far as I know, you'd need to deal with this in steps. The first step is to create a bound function -- i.e., take the function you specify, and create an object that, when you invoke it, in turn invokes the specified function with the specified parameters. Using Boost/TR1/C++0x bind, that much would look something like this:
std::tr1::function<void (int)> func(std::tr1::bind(&TextBox::changColor, this, red));
That makes func an object that will invoke TextBox::changeColor(red) when it's called. There is one minor problem with this though: func is an object, not really a function. Syntactically, using it looks like calling a function, but that's an illusion created by the C++ compiler; trying to pass that object's address to something that will use it as the address of a function will fail (probably pretty spectacularly). Unfortunately, at least in Windows, there's no way to designate an arbitrary parameter that will be passed to a timer callback function (though you could probably manage to do it in the nIdEvent parameter with some really gross casting, something like:
void callback(HWND, UINT, UINT_PTR f, DWORD) {
typedef std::tr1::function<void (int)> function;
function *func = reinterpret_cast<function *>(f);
(*func)();
}
To make this a bit cleaner, instead of casting the address to an unsigned integer, I'd consider saving the address of the callback in an array, and passing its index in the array instead:
void callback(HWND, UINT, UINT_PTR f, DWORD) {
callback_functions[f]();
}
That leaves the really non-portable part: actually getting the system to invoke that function after the right length of time. Though most modern systems have one, each is still unique. Under Windows (for one example) you could do something like this:
callback_functions[++N] = func;
SetTimer(hWnd, N, 30, callback);
For such a simple idea, that's all too ugly and complex an answer, but I honestly don't know of anything much less complex that'll work. If you have almost any reasonable choice in the matter, I'd use something else. Also note that this is really a stream-of-consciousness sketch -- none of the code has been compiled, much less really tested. I can't see a good reason the general idea shouldn't work, but it might take a fair amount of effort to flesh it out to something that really does (e.g., I've mostly neglected management of the "callback_functions" array).
Before asking you my question directly, I'm going to describe the nature of my prolem.
I'm coding a 2D simulation using C++/OpenGL with the GLFW library. And I need to manage a lot of threads properly. In GLFW we have to call the function:
thread = glfwCreateThread(ThreadFunc, NULL); (the first parameter is the function that'll execute the thread, and the second represents the parameters of this function).
And glfwCreateThread, has to be called every time! (ie: in each cycle). This way of working, doesn't really help me, because it breaks the way i'm building my code because i need to create threads out of the main loop scope. So I'm creating a ThreadManager class, that'll have the following prototype :
class ThreadManager {
public:
ThreadManager();
void AddThread(void*, void GLFWCALL (*pt2Func)(void*));
void DeleteThread(void GLFWCALL (*pt2Func)(void*));
void ExecuteAllThreads();
private:
vector<void GLFWCALL (*pt2Func)(void*)> list_functions;
// some attributs
};
So for example, if I want to add a specific thread I'll just need to call AddThread with the specific parameters, and the specific function. And the goal is just to be able to call: ExecuteAllThreads(); inside the main loop scope. But for this i need to have something like:
void ExecuteAllThreads() {
vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter_end = list_functions.end();
for(vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(&(iter*), param);
}
}
And inside AddThread, I'll just have to add the function referenced by the pt2Func to the vector : list_functions.
Alright, this is the general idea of what i want to do.. is it the right way to go ? You have a better idea ? How to do this, really ? (I mean the problem is the syntax, i'm not sure how to do this).
Thank you !
You need to create threads in each simulation cycle? That sounds suspicious. Create your threads once, and reuse them.
Thread creation isn't a cheap operation. You definitely don't want to do that in every iteration step.
If possible, I'd recommend you use Boost.Thread for threads instead, to give you type safety and other handy features. Threading is complicated enough without throwing away type safety and working against a primitive C API.
That said, what you're asking is possible, although it gets messy. First, you need to store the arguments for the functions as well, so your class looks something like this:
class ThreadManager {
public:
typedef void GLFWCALL (*pt2Func)(void*); // Just a convenience typedef
typedef std::vector<std::pair<pt2Func, void*> > func_vector;
ThreadManager();
void AddThread(void*, pt2Func);
void DeleteThread(pt2Func);
void ExecuteAllThreads();
private:
func_vector list_functions;
};
And then ExecuteAllThreads:
void ExecuteAllThreads() {
func_vector::const_iterator iter_end = list_functions.end();
for(func_vector::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(iter->first, iter->second);
}
}
And of course inside AddThread you'd have to add a pair of function pointer and argument to the vector.
Note that Boost.Thread would solve most of this a lot cleaner, since it expects a thread to be a functor (which can hold state, and therefore doesn't need explicit arguments).
Your thread function could be defined something like this:
class MyThread {
MyThread(/* Pass whatever arguments you want in the constructor, and store them in the object as members */);
void operator()() {
// The actual thread function
}
};
And since the operator() doesn't take any parameters, it becomes a lot simpler to start the thread.
What about trying to store them using boost::function ?
They could simulate your specific functions, since they behave like real objects but in fact are simple functors.
Consider Boost Thread and Thread Group
I am not familiar with the threading system you use. So bear with me.
Shouldn't you maintain a list of thread identifiers?
class ThreadManager {
private:
vector<thread_id_t> mThreads;
// ...
};
and then in ExecuteAllThreads you'd do:
for_each(mThreads.begin(), mThreads.end(), bind(some_fun, _1));
(using Boost Lambda bind and placeholder arguments) where some_fun is the function you call for all threads.
Or is it that you want to call a set of functions for a given thread?