New thread on a class function - c++

I want to make a class that contains a bunch virtual functions which are called on different events. I have the class already but how do I start those functions as new threads? I can manage to do this on global functions only. I want my class to look like this:
class Callbackk{
CallBack(){};
virtual ~Callback(){};
virtual void onSomething();
virtual void onElse(Someclass x);
virtual void onBum(Newclass nc);
}
of course each function would be called with different parameters but the idea is that I want those functions to be void and be able to accept some arguments.
Using: Visual Studio 2010

Different threading mechanisms are using different syntax for this case.
I will supply the example for boost::thread library.
Obviously, you have to bind your function to some class instance for it to be called. This can be accomplished the following way:
// Thread constructor is a template and accepts any object that models 'Callable'
// Note that the thread is automatically started after it's construction.
// So...
// This is the instance of your class, can possibly be some derived
// instance, whatever actually.
Callback* callback_instance;
// This construction would automatically start a new thread running the
// 'onElse' handler with the supplied arguments.
// Note that you may want to make 'x' a member of your thread controlling
// class to make thread suspending and other actions possible.
// You also may want to have something like 'std::vector<boost::thread>' created
// for your case.
boost::thread x(boost::bind(&Callback::onElse, callback_instance, ARGUMENTS));

My suggestion is that you add some static member functions in your class to do so. For example, you could add a static member function called onSomethingThread, which do the same things you want originally by the function onSomething. Then in the function onSomething, you simply create a new thread and run onSomethingThread in it.

Related

How to get all the public methods of a c++ subclass and put them in a vector?

I'm building a c++ aplication where the user create a class like that:
class MyClass : public FrameworkClass {
/** Some user attributes and methods
*
*/
class ROUTINE {
private:
void privateMethod();
public:
void method1();
void foo();
void AnyName();
}};
The idea is that all public methods of the ROUTINE subclass are executed on separate threads in a loop. Currently, the user himself has to register all the methods pushing them in a vector that the framework will iterate starting the threads, but I want to know if there is any way to make this process automatic, that is, create the array automatically since all the methods inside the ROUTINE subclass should always run this way, preferably in a non-intrusive way like a macro.
OBS:
the loop is something simple like:
void routineLoop() {
while(Framework::IsRunning) {
//call the method
}
}
and it's alreandy working, the only problem it's the usability.
It is currently not possible to retrieve a list of the member functions of a class in C++ in any form. Reflection capabilities in current C++ are very limited.
You will always need to have the user provide you with at least the member function names if not member function pointers as you seem to be doing now.
To make it easier for the user, e.g. a macro could be provided which creates an array of member function pointers with a fixed name from a list of member function names in the macro arguments. Then the user only needs to place the macro inside the class definition and list the member function names and you can retrieve it as a member with the known name.

Disable code based on existence of Constructor

I am trying to disable some code based on whether the code creates an Object or not (or calls a function or whatever). Sounds a bit strange, I know.
In my library it is possible to create 2 objects, each object needs an interrupt service routine like:
ISR(TIMER0_COMPA_vect) {
// do some stuff if the interrupt happens
}
The ISR can only be created once but it could be possible that the user just creates one or none of my objects, so the ISR shouldn't be created in the first place to not block the creation of one by the user.
I know it would be easy to encapsulate the code like this
#ifdef OBJECT1
ISR(TIMER0_COMPA_vect) {
// do some stuff if the interrupt happens
}
#endif
but that forces the user to keep track of the objects she/he created.
Is there an option to let the preprocessor decide if, let's say, the constructor is called once or even existent?
A little bit like something like this
Foo:Foo() {
#define USE_FOO
//Some code
}
#ifdef USE_FOO
ISR(TIMER0_COMPA_vect) {
// do some stuff if the interrupt happens
}
#endif
EDIT:
Based on the answers i got, I try to clarify my question a bit:
Foo1:Foo1() {
//Some object constructor code
}
Foo2:Foo2() {
//Some object constructor code
}
ISR(TIMER1_COMPA_vect) {
//some interrupt code
}
ISR(TIMER2_COMPA_vect) {
//some interrupt code
}
int main() {
Foo2 foo2;
}
If this is the code we are talking about, the function ISR(TIMER1_COMPA_vect) shouldn't be compiled at all. The ISR MUST be absent.
PS: if you need more information, I can provide more but I tried to keep the problem as basic as possible
Typically what you would do for this type of situation is compile the code for such an object into a library. The linker is smart enough to detect if your main program depends on any function from the library. If it does, it will load the entire compilation unit (i.e. the .c or .cpp file) of that function into your program. Any ISRs that it finds in the compilation unit will be added to your program. If you don't use any functions from the library, the ISRs will not be added.
For example, put something like this in foo1.h:
#pragma once
class Foo1 {
public:
Foo1();
};
Put something like this in foo1.cpp:
#include <foo1.h>
ISR(TIMER1_COMPA_vect) {
}
Foo1::Foo1() {
}
Now you should compile foo1.cpp into foo1.o using avr-gcc. Next, use avr-ar to store foo1.o in an archive named foo1.a. Then, compile your main program with avr-gcc, and provide foo1.a as an argument. Make sure the foo1.a argument comes after main.cpp.
You may need to create a singleton. There are numerous examples. A singleton is a class that constructs itself, once only. The constructors are private and a static method checks a "global" variable to see if the class has already been constructed if not it will construct itself once only. You will may need to consider threading issues although for construction you can simply reference the class early before you have created multiple classes. For multiple users of an interrupt you typically use some sort of dispatcher that the objects register with and then all classes interested in the interrupt are called. The dispatcher may be a singleton. Typically a client of a dispatcher implements an interface. As part of registration with the dispatcher the class tell the dispatcher its "this" pointer and the dispatcher can call the methods implemented from the interface as though they were called as normal. There is no need for the client to have static methods. There are probably patterns for this stuff but I cannot name any.
As you stated your problem sounds strange but if you want to do something only once let's say in the constructor you can go with a simple but very ugly thing like this using local static variable
Foo:Foo() {
static bool init = true;
if( init ) {
//Some code for ISR init
init = false;
}
}
This way your special ISR initialization will take place only once, whatever the number of Foo object you or your user construct
EDIT:
I think there is no way to achieve what you want, at least no clean way.
Imo your problem comes from your ISR macro which actually does two things:
Initializing your ISR vector (ISR registration)
Defining your ISR handler (ISR handler)
To solve your problem I suggest you to split this into two macros then:
ISR registration goes in you Foo1 / Foo2 constructor -> use a global field or whatever mechanism to initialize only once or keep track internally of what has happened or so
Keep another macro ISR_HANDLER with only the handler definition
Your handlers can then remain defined and should have no influence if it is not registered by any of the Foo classes

Custom function per-instance of a class (C++)

I have a class "EngineObject"
I would like to have a custom function for that class which may vary by instance of that object.
Right now i'm doing it with function pointers like this:
class EngineObject{
public:
bool (*Update)(EngineObject* Me);
bool (*Prep)(EngineObject* Me);
bool (*OnCollide)(EngineObject* Me, EngineObject* Them);
};
As you may have noticed, this requires me to do something quite atrocious. I have to feed the object to its member function... Digusting
it also requires me to write extra getters and setters that I really don't want to be accessible from any other part of the code, just so I can see the "innards" of the EngineObject from functions passed in via function pointer
Is there some way I could write a function that I could apply, per instance of the object, that could access the privates of the object, and without having to pass the object to the function?
FOR CLARITY:
Let's say I want two EngineObjects
EngineObject1 = new EngineObject();
EngineObject2 = new EngineObject();
I'd like to set the update function of 1 to (something) and 2 to (something else)
EngineObject1.Update = &foo;
EngineObject2.Update = &bar;
I cannot simply use virtual functions and inheritance because these functions need to be able to be assigned and re-assigned at run-time.
The problem is that I need access to privates from these functions, and in order to do that i'd need to write public getters and setters for everything, which sort of erases the need for making anything private...
context:
The reason i'm doing this is to allow dynamic type generation at run time without introspection, to maximize what can be done from a scripting interface, and reduce the total number of functions that need to be bound to the scripting interface and reduce the learning curve for users.
Basically, you'd have an EngineObjectTemplate class which specified what all these functions would be for this dynamically generated type, and then the EngineObject would be created using a function in the EngineObjectTemplate class
EngineObjectTemplates may be generated at run time by combining various pre-written C++ functions (Update, Prep, OnCollide). This would be a "type" of sorts.
If a user wishes to write a new update, prep, or oncollide function, they could choose to write and compile it into a DLL file and add it to the project (Which my EXE will read and add to a list of function pointers, which can be referenced by string names in the scripting language to assign to templates and/or therefore engineobjects), or they could script it in the scripting language I choose, which would of course be slower.
Another reason why i'm doing it this way is that i'd like to avoid inheritance because it is HELL to make inherited classes work with the scripting wrapper I plan on using.
What you want to do is not possible because what you are actually asking is essentially:
"How can I make code living outside of a class access private members".
If this was possible without jumping through some ugly, ugly hoops, then it would mean that private is broken.
The only way to access private members of a class is that the class explicitly gives you access to them, either from its interface, or by marking the code as friend as part of its declaration.
Either the members are private, or they are not. You can't have it both ways.
N.B. This is a bit of a lie, as you can do some tricks in some exceptional corner-cases, but these should only be used as a last resort.
You can create a callable object class that overrides the () operator. A base class would provide the template for what the replaceable function receives as parameters with child classes implementing that particular method. Then you declare the callable class as a friend to your owning class. Like the following:
class EngineObject;
class Callable;
class EngineObject
{
private:
int member;
Callable *func;
public:
EngineObject(int m, Callable *f) : member(m), func(f) {}
int Call(int p)
{
return func(p);
}
friend Callable;
};
class Callable;
{
public:
int operator(EngineObject *eo, int param)
{
eo->member = param;
return param;
}
};
In the above, I also further hid the variable function call behind a wrapper so that an outside function doesn't need to pass the object as a parameter as well.

Using pthread on implementation of a function which is part of an object (that is passed as parameter)

We're currently trying to do some multithreaded work using pthreads
We have a class that looks like this.
class TestObj{
public:
void runThreaded1(int x, int y);
}
The class holds two functions which we need to run in a multithreaded environment, i.e have multiple threads running "runThreaded1".
We have another class which looks something like this:
class RunThreaded{
public:
RunThreaded(ThreadObj& object);
void run(int x, int y);
}
We would like to have multiple instances of the RunThreaded class. Each instance would have its own pthread that runs the implementation inside the ThreadObject that is passed on to it.
So essentially a run will look like this:
(let's say we have an instance of ThreadObj named obj in hand)
RunThreaded t1 = new RunThreaded(obj);
RunThreaded t2 = new RunThreaded(obj);
t1.run(4, 5);
t2.run(6, 7);
t1.run(8, 9);
t2.run(10, 11);
So in the example above we have two objects that each run the same implementation of runThreaded1 but on two different pthreads
Two questions:
1) What is the best way to create and use the pthread with our constraints? (i.e running a thread on an implementation of a function that is a member of some object). We found this question after some googling:
pthread function from a class
and wonder if those are the only solutions for doing it. We started implementing it but ran into some issues
2) Is it possible to create the pthread once and then call the run method every time without using pthread_create? We know that pthread_create creates and runs the thread. We want to create the thread only once but be able to "run" the threaded procedure multiple times but don't know if such a pthread_run function exists
Thank you very much!

Howto Execute a C++ member function as a thread without Boost?

I am using a small embedded RTOS which supports threads. I am programming in C++ and want to create a class that will allow me to run an arbitrary member function of any class as a thread. The RTOS does not directly support creating threads from member functions but they work fine if called from withing a thread. Boost::thread is not available on my platform.
I am currently starting threads in an ad-hoc fashion through a friend thread_starter() function but it seems that I must have a seperate one of these for each class I want to run threads from. My current solution of a thread base class uses a virtual run() function but this has the disadvantage that I can only start 1 thread for a class and that is restricted to the run() function + whatever that calls in turn (ie I cannot run an arbitrary function from within run() elegantly)
I would ideally like a class "thread" that was templated so I could perform the following from within a class "X" member function :
class X
{
run_as_thread(void* p)';
};
X x;
void* p = NULL;
template<X>
thread t(x, X::run_as_thread, p);
//somehow causing the following to be run as a thread :
x->run_as_thread(p);
Sorry if this has been done to death here before but I can only seem to find references to using Boost::thread to accomplish this and that is not available to me. I also do not have access to a heap so all globals have to be static.
Many thanks,
Mike
If your compiler is modern enough to support the C++11 threading functionality then you can use that.
Maybe something like this:
class X
{
public:
void run(void *p);
};
X myX;
void *p = nullptr;
std::thread myThread(std::bind(&X::run, myX, p));
Now X::run will be run as a thread. Call std::thread::join when the thread is done to clean up after it.
Assuming your RTOS works a bit like pthreads, and you don't have C++11 (which probably makes assumptions about your threading support) you can use this sort of mechanism, but you need a static method in the class which takes a pointer to an instance of the class. Thus (roughly)
class Wibble
{
public:
static void *run_pthread(void *me)
{
Wibble *x(static_cast<Wibble *>(me));
return x->run_thread_code();
}
private:
void *run_thread();
};
Wibble w;
pthread_create(&thread, &attr, Wibble::run_pthread, &w);
Passing arguments is left as an exercise to the reader...
This can be templatised with a bit of effort, but it's how the guts is going to need to work.
Have a look at my post on passing C++ callbacks between unrelated classes in non-boost project here.
It sounds like what you are asking is a way to run an arbitrary member function on a class asynchronously. I take it from your comment about the virtual run() function:
"this has the disadvantage that I can only start 1 thread for a class"
...to mean that you do not like that option because it causes all function calls to execute in that thread, when what you want is the ability to have individual function calls threaded off, NOT just create an object-oriented thread abstraction.
You should look into a thread pooling library for your target platform. I can't offer any concrete suggestions given no knowledge of your actual platform or requirements, but that should give you a term to search on and hopefully get some fruitful results.