Member-Function Pointer in Threads - c++

I have made a class which uses an array of member-functions to initialize an array of threads.
I do not know how to pass the function pointer to the thread constructor. There is few documentation about this topic.
class.h
#define N_FUNCTIONS 23
class TradingData
{
public:
void EXECUTE();
void Book();
void Charts();
void Company();
void Dividends();
void Earnings();
void EffectiveSpread();
void Financials();
void KeyStats();
void LargestTrades();
void List();
void Logo();
void News();
void OHLC();
void Peers();
void Previous();
void Price();
void Quote();
void Relevant();
void Splits();
void TimeSeries();
void VolumeByVenue();
void S_Previous();
void S_Symbols();
private:
std::thread p_thread[N_FUNCTIONS];
typedef void (TradingData::*overall)();
overall p_overall[N_FUNCTIONS] = {
&TradingData::Book,
&TradingData::Charts,
&TradingData::Company,
&TradingData::Dividends,
&TradingData::Earnings,
&TradingData::EffectiveSpread,
&TradingData::Financials,
&TradingData::KeyStats,
&TradingData::LargestTrades,
&TradingData::List,
&TradingData::Logo,
&TradingData::News,
&TradingData::OHLC,
&TradingData::Peers,
&TradingData::Previous,
&TradingData::Price,
&TradingData::Quote,
&TradingData::Relevant,
&TradingData::Splits,
&TradingData::TimeSeries,
&TradingData::VolumeByVenue,
&TradingData::S_Symbols,
&TradingData::S_Previous
};
class.cpp
void TradingData::EXECUTE()
{
for (int i = 0; i < N_FUNCTIONS; i++) {
p_thread[i] = std::thread((this->*p_overall[i])()); //here is the problem
}
for (int i = 0; i < N_FUNCTIONS; i++) {
p_thread[i].join();
}
std::cout << "finished successfully" <<std::endl;
}
I got the next error:
Error C2440 '': cannot convert from 'void' to 'std::thread'

You should write call;
p_thread[i] = std::thread(TradingData::p_overall[i], this);
If you call a member function the class name will be include in the call.

p_thread[i] = std::thread((this->*p_overall[i])());
This will pass the return value of the member function being called to the thread constructor. But as you do not return something callable, this will even fail to compile, of course.
Be aware that the object on which you call a member function actually is passed (transparently for you) as first parameter to the function being called. And this is what you need to reflect when creating the thread:
p_thread[i] = std::thread(p_overall[i], *this);
The thread upon starting will now call the member function with *this as first argument. Be aware that member functions in reality accept a reference, although this, inside the function, is defined as pointer, thus dereferencing the this-pointer...
Sometimes, a lambda can be useful, which looks like this here:
std::thread t(this, i {(this->*p_overall[i])(); });
Sure, overkill in given case, but might be useful in other situation sometime in future...

Related

Can you pass a function so you can later call it?

I want to have objects with one method which calls a function (but every object should have a different function to call). I will try to show you what I mean by showing an example:
class Human
{
public:
void setMyFunction(void func); // specify which function to call
void callMyFunction(); // Call the specified function
};
void Human::setMyFunction(void func) // ''
{
myFunction = func;
}
void Human::callMyFunction() // ''
{
myFunction();
}
void someRandomFunction() // A random function
{
// Some random code
}
int main()
{
Human Lisa; // Create Object
Lisa.setMyFunction(); // Set the function for that object
Lisa.callMyFunction(); // Call the function specified earlier
}
This code (obviously) doesn't work but I hope you understand what I am trying to accomplish.
MfG, TPRammus
You might use std::function.
#include <functional>
class Human
{
std::function<void()> mFunc;
public:
void setMyFunction(std::function<void()> func) { mFunc = func; }
void callMyFunction() { if (mFunc) mFunc(); }
};
Demo
I would suggest using a simple function pointer. Just do this:
class Human
{
public:
using func_t = void (*)();
void setMyFunction(func_t f) {
func = f;
}
void callMyFunction() {
func();
}
private:
func_t func;
};
The reasons why one might prefer function pointers to std::function are:
Performance. Calling std::function tends to be slower, than calling a function by pointer.
std::function needs truly ugly syntax when one needs to bind it to an overloaded function.
Example:
void foo();
void foo(int x = 0);
void check() {
Human h;
h.setMyFunction(&foo);
}
Will fail to compile.

Getting function name from stack frame

Suppose I have some functions:
void func1 (){
...
}
void func2(){
...
}
int main(){
func1();
//check called functions
return 0;
}
I'd like to check which function was called. Here it is func1. I can make one more special checker-function for this. But is it possible to get the name of the function, which was called from stack frame and how?
I recommend not calling the functions directly, but instead use function objects:
struct func_base
{
virtual const std::string& get_function_name(void) const = 0;
virtual void execute(void) = 0;
void operator() (void)
{
execute();
}
};
This would allow you to retrieve the name of the function that you executed.
By the time the code is compiled, this information is not known anymore. You can use ad hoc solutions, such as return function name from the function itself (use __FUNCTION__ macro to make your life easier). This will be very ugly, of course.

pointer on method as an argument

To avoid code duplication, I'm tring to pass pointers to functions as arguments of a static method.
I have a class (Geo) with only static methods. One of this methods (+++Geo::traceRay(+++)) should just display(Geo::display(+++)) few things, then return an int.
Another class (Las) needs to use the Geo::traceRay(+++) method, but should display(Las::display(+++)) someting else.
So I try to pass a pointer to function argument to the Geo::traceRay(+++, pointer to function) method. the pointed functon will the right "display()" method.
Up to now, passing the first pointer to display() is not an issue, but I can't find how to do it with the second one.
class Geo
{
public:
static bool display(int pix);
static int traceRay(int start, int end, bool (*func)(int) = &Geo::display); // no issue with this default parameter
};
class Las
{
public:
bool display(int pix);
void run();
};
int Geo::traceRay(int start, int end, bool (*func)(int))
{
for (int i = start; i < end ; ++i )
{
if((*func)(i)) return i;
}
return end;
}
bool Geo::display(int pix)
{
cout << pix*100 << endl;
return false;
}
bool Las::display(int pix)
{
cout << pix << endl;
if (pix == 6) return true;
return false;
}
void Las::run()
{
bool (Las::*myPointerToFunc)(int) = &display; // I can just use display as a non member class, but it should stay a member
Geo::traceRay(0,10, myPointerToFunc); // issue here!
}
int main()
{
Geo::traceRay(0,10); // use the "normal display" = the default one// OK
Las myLas;
myLas.run();
return 0;
}
You can't pass a member function pointer as a function pointer. I presume making Las::display static is not an option. In that case, I would suggest taking a std::function and using std::bind to bind the current instance:
static int traceRay(int start, int end, std::function<bool(int)> func = &Geo::display);
...
Geo::traceRay(0,10, std::bind(&Las::display, this, std::placeholders::_1));
Also, in both cases, you can call func by:
func(i);
No need to dereference it first.
What Chris suggests is great if that's as far as it goes.
Another approach to this, which would be beneficial if you have several shared functions like that, would be to use an interface (with a virtual method Display(+++)) with two implementations, put an instance of the implementation in question in each of Geo and Las (or Las could directly implement the interface). Then traceRay takes a reference to the interface base class and calls the display method on it.

C++ calling a function from a vector of function pointers inside a class where the function definition is in main

Alright, in my main i have:
void somefunction();
int main()
{
//bla bla bla
SomeClass myclass = SomeClass();
void(*pointerfunc)() = somefunction;
myclass.addThingy(pointerfunc);
//then later i do
myclass.actionWithDiffrentOutcomes();
}
void somefunction()
{
//some code
}
and in the class:
class SomeClass()
{
public:
void addThingy(void (*function)());
void actionWithDiffrentOutcomes();
private:
std::vector<void (**)()> vectoroffunctions;
}
SomeClass::addThingy(void (*function)())
{
vectoroffunctions.push_back(&function);
}
SomeClass::actionWithDiffrentOutcomes()
{
(*vectoroffunctions[0])();;
}
I'm sort of new-ish to pointers, but I read over my c++ books, googled, ext. and this seems correct, compiles, runs but when I call "actionWithDiffrentOutcomes()" I get an access violation. I'm not sure what to do. it seems correct, but something is obviously wrong. So how can I call a function from within a class when the definition is in another?
I'm doing it this way because i cannot hard-code every option into a switch statement.
Your code is almost correct. Your vector is mistakenly holding pointers to pointers to functions rather than simply pointers to functions. addThingy is adding the address of the function pointer in to the vector, but that pointer goes out of scope in the next line.
Change your code as follows:
//Store pointers to functions, rather than
//pointers to pointers to functions
std::vector<void (*)()> vectoroffunctions;
SomeClass::addThingy(void (*function)())
{
//Don't take the address of the address:
vectoroffunctions.push_back(function);
}
Also, you have a lot of syntax errors in the rest of the code which should stop the code from even compiling.
The problem is here:
vectoroffunctions.push_back(&function);
You're adding address of the local variable. The local variable gets destroyed once you return from the function. The address which the vector stores points to a destroyed object which is why you get "access violation" error at runtime.
To fix this, do this:
First change this
std::vector<void (**)()> vectoroffunctions;
to this:
std::vector<void (*)()> _functions; //vector of function-pointer-type
//I changed the name also!
which is practically same as:
std::vector<void()> _functions; //vector of function-type
Now do this:
_functions.push_back(function); //add copy!
To make it more flexible, you could use template along with std::function as:
class A
{
public:
template<typename Function>
void add(Function && fn)
{
_functions.push_back(std::forward<Function>(fn));
}
void invoke_all()
{
for(auto && fn : _functions)
fn();
}
private:
std::vector<std::function<void()>> _functions;
};
Now you can use it to store functions as well as functors:
void myfunction() { std::cout << "myfunction" << std::endl ; }
struct myfunctor
{
void operator()() { std::cout << "myfunctor" << std::endl ; }
};
A a;
a.add(myfunction); //add function
a.add(myfunctor()); //add functor!
a.invoke_all();
Output (Online Demo):
myfunction
myfunctor
Hope that helps.
Function pointers are much more legible with typedefs:
typedef void (*RequiredFunction)();
Then you can declare addThingy() like this:
void addThingy(RequiredFunction function);
And vectoroffunctions like so:
std::vector<RequiredFunction> vectoroffunctions;
The definition of addThingy will be:
void SomeClass::addThingy(RequiredFunction function)
{
vectoroffunctions.push_back(function);
}
And your main() would look more like:
int main()
{
SomeClass sc;
RequiredFunction pointerfunc = somefunction;
sc.addThingy(pointerfunc);
sc.actionWithDiffrentOutcomes();
}
Far fewer *s and &s with which to make mistakes!

Static function needing to deal with members of a C++ class

I have to make some kind of bridge between two pieces of software, but am facing an issue I don't know how to deal with. Hopefully someone will have interesting and (preferably) working suggestions.
Here is the background : I have a C++ software suite. I have to replace some function within a given class with another function, which is ok. The problem is that the new function calls another function which has to be static, but has to deal with members of the class. This is this second function which is making me mad.
If the function is not static I get the following error :
error: argument of type ‘void (MyClass::)(…)’ does not match ‘void (*)(…)’
If I set it to static I get either the following error :
error: cannot call member function ‘void
MyClass::MyFunction(const double *)’ without object
or
error: ‘this’ is unavailable for static member functions
depending on if I use or not the "this" keyword ("Function()" or "this->Function()").
And finally, the class object requires some arguments which I cannot pass to the static function (I cannot modify the static function prototype), which prevents me to create a new instance within the static function itself.
How would you deal with such a case with minimal rewriting ?
Edit : Ok, here is a simplified sample on what I have to do, hoping it is clear and correct :
// This function is called by another class on an instance of MyClass
MyClass::BigFunction()
{
…
// Call of a function from an external piece of code,
// which prototype I cannot change
XFunction(fcn, some more args);
…
}
// This function has to be static and I cannot change its prototype,
// for it to be passed to XFunction. XFunction makes iterations on it
// changing parameters (likelihood maximization) which do not appear
// on this sample
void MyClass::fcn(some args, typeN& result)
{
// doesn't work because fcn is static
result = SomeComputation();
// doesn't work, for the same reason
result = this->SomeComputation();
// doesn't work either, because MyClass has many parameters
// which have to be set
MyClass *tmp = new MyClass();
result = tmp->SomeComputation();
}
Pointers to non-static member functions are a bit tricky to deal with. The simplest workaround would just be to add an opaque pointer argument to your function which you can then cast as a pointer to 'this', then do what you need with it.
Here's a very simple example:
void doSomething(int (*callback)(void *usrPtr), void *usrPtr)
{
// Do stuff...
int value = callback(usrPtr);
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(myCallback, this);
}
private:
int value_;
static int myCallback(void *usrPtr)
{
MyClass *parent = static_cast<MyClass *>(usrPtr);
return parent->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
In this example myCallback() can access the private value_ through the opaque pointer.
If you want a more C++-like approach you could look into using Boost.Function and Boost.Bind which allow you to pass non-static member functions as callbacks:
void doSomething(boost::function<int ()> callback)
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(boost::bind(&MyClass::myCallback, this));
}
private:
int value_;
int myCallback()
{
return value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
If you really can't change the function prototype you could use a global pointer, but that opens up all sorts of issues if you will ever have more than one instance of your class. It's just generally bad practice.
class MyClass;
static MyClass *myClass;
void doSomething(int (*callback)())
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
myClass = this;
doSomething(myCallback);
}
private:
int value_;
static int myCallback()
{
return myClass->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
Following spencercw's suggestion below the initial question I tried the "static member variable that you set to point to this" solution (the global variable would have been tricky and dangerous within the context of the software suite).
Actually I figured out there was already something like this implemented in the code (which I didn't write) :
static void* currentObject;
So I just used it, as
((MyClass*)currentObject)->SomeComputation();
It does work, thanks !!!
non-reentrant and non-thread-safe way is to pass "this" address using global variable.
You can move the result = SomeComputation(); out of your static function and place it in BigFunction right before your call to the static function.