I want to create a thread of the function ahrs thats in my AHRS class. This function is in an infinite loop and calcs something the whole time and puts those calculations in variables. I want to pass those variables to my PID
int main() {
AHRS* a = new AHRS();
std::thread ahrs(a->ahrs());
PID* p = new PID();
float pitch;
while(1) {
pitch = a->getPitch();
std::cout << "pitch: " << pitch << " pid: " << p->getError(0, pitch, 1) << std::endl;
usleep(100000);
}
}
but i get the error
main_ahrs.cpp: In function ‘int main()’:
main_ahrs.cpp:26:28: error: invalid use of void expression
my ahrs.cpp looks like this:
#include "AHRS.h"
AHRS::AHRS() {
//something
}
AHRS::~AHRS() {}
void AHRS::ahrs() {
//something
while(1) {
//something
}
}
float AHRS::getPitch() {
//return something
}
float AHRS::getRoll() {
//return something
}
float AHRS::getYaw() {
//return something
}
thanks for your help
a->ahrs()
That is not how you name a function. That is how you call an expression and use its result for something. The result of the function is of void type (that is, there isn't one) so using this function call as an expression (and certainly for a function reference/object/handle/wrapper/pointer!) is just not going to work.
The function is called AHRS::ahrs.
A further complication is that it is a member function, so you have to bind the implicit this parameter, like so:
std::thread ahrs(std::bind(&AHRS::ahrs, a));
The binding creates a sort of pseudo-function reference that already has the first argument sorted out for you, so that you (or, in this case, the thread code, which has no ability or desire to guess what the object instance should be) does not need to.
Conveniently, thread can do the binding for you, though, so:
std::thread ahrs(&AHRS::ahrs, a);
should suffice.
Try like this:
#include <functional>
and then:
std::thread ahrs(std::bind(&AHRS::ahrs, a));
The way you are doing, you are calling the a->ahrs() method, that returns void. You must pass in to std::thread something that can be called: a function pointer, or something like that, not void.
In this case of my suggestion, you will pass to std::thread the return from std::bind, that is a callable object built with a pointer to the method and a pointer to the AHRS object.
Lambda is your friend.
int main() {
AHRS* a = new AHRS();
std::thread ahrs(a->ahrs());
what the above does is it calls a->ahrs() (in main), takes its return value and passes it to the thread constructor. This isn't what you want.
Instead:
AHRS* a = new AHRS();
std::thread ahrs([a]{a->ahrs();});
will create a closure (or lambda) that consists of "do a call of a->ahrs()".
It then passes that closure to std::thread, which runs it on a different thread.
The [a] says "this is a closure, and it captures a (copy of) a". Then the body {a->ahrs();} says what the closure does.
In general, passing lambdas to std::thread is easier to reason about than passing the alternatives. There is a modest problem in that move-parameters require C++14 to work.
Using std::bind or the variardic constructor of std::thread are alternatives. I prefer passing code to passing data in this case, and passing a lambda closure is basically passing code.
Related
I have trouble to pass an argument to my dispatch queue that takes a function pointer as a parameter. I have implemented a Dispatch Queue like this tutorial
typedef std::function<std::string( const std::array<float, kMaxSamples> &)> fp_t;
class DispatchQueue {
public:
DispatchQueue(std::string name, size_t thread_cnt = 1);
~DispatchQueue();
//move
void dispatch(fp_t && item); //Take the typedef defined above
private:
std::string _name;
std::queue<fp_t> _q;
std::vector<std::thread> _threads;
void dispatch_thread_handler(void);
std::mutex _lock;
std::condition_variable _cv;
bool _quit;
};
My std::function takes an std::array as a parameter.
Then, later in my code I add in the queue this particular job to process this argument.
queue->dispatch(std::bind(&AudioRecordEngine::run, mRecordingCallbackImp.getAudioData()));
The dispatch function is defined as:
void DispatchQueue::dispatch(fp_t &&item)
{
std::unique_lock<std::mutex> lock(_lock);
_q.push(item);
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lock.unlock();
_cv.notify_one();
}`
Maybe it is too complicated for this use case, I probably don't know how to do better.
I would greatly appreciate suggestion and help. I am stuck for quite a while.
Thanks a lot
EDIT:
The problem I am facing is at compilation time:
no viable conversion from '__bind<std::__ndk1::__bind<std::__ndk1::basic_string<char, std::__ndk1::char_traits, std::__ndk1::allocator > (AudioRecordEngine::*)(const std::__ndk1::array<float, 44100> &), std::__ndk1::array<float, 44100> > >' to 'fp_t' (aka 'function<basic_string<char, char_traits, allocator > (const array<float, kMaxSamples> &)>')
It seems that my std::function do not support the argument I am passing. The problem look like I do not use the std::bind properly.
Basically I would like to pass to my dispatch function the function pointer with the given argument.
EDIT 2:
The AudioRecordEngine::run is defined as:
std::string AudioRecordEngine::run(const std::array<float, __NUM_SAMPLES__> & audioData) {
std::thread::id this_id = std::this_thread::get_id();
LOGD("In the thread ID %zu \n", this_id);
//double freq = FFTNativeWrapper::fftEntryPoint(audioData);
//LOGD("In the Thread, FFT analysis == %zu \n", freq);
return "from thread";
}
std::array<float, kMaxSamples> RecordingCallbackImp::getAudioData() {
return mData;
}
Inside the implementation of DispatchQueue, functional objects of type fp_t are invoked as fn(), so fp_t should be std::function<std::string()> or std::function<void()>. There should be no const std::array& parameter.
std::bind should give you something that takes no parameters. Your std::bind is almost correct. When you want to invoke a non-static member function, you need an object. That object, in the form of a pointer or a reference, should be the second argument of std::bind:
AudioRecordEngine engine;
queue->dispatch(std::bind(
&AudioRecordEngine::run,
std::ref(engine),
mRecordingCallbackImp.getAudioData()
));
Be careful about engine life time.
Alternatively, you can use a lambda function instead of std::bind:
AudioRecordEngine engine;
queue->dispatch([&] {
engine.run(mRecordingCallbackImp.getAudioData());
});
This and the previous approaches differ by the moment when getAudioData() is called: in 2, the result of getAudioData() execution is stored inside the functional object returned by std::bind, in 3, getAudioData() is invoked just before run is called.
Minimal example
I have a function that acts as a "function dispatch." This function contains a variable named next_func, which is initialized to the first function to load. Then, inside an infinite loop, the next_func is set to the return value of itself.
My question is, besides using auto, what type does next_func need to be? Here's some conceptual code (using auto) to give an idea of what I'm looking for:
void FunctionDispatch()
{
auto next_menu = first_menu;
while (next_menu != app_exit)
{
next_menu = next_menu();
}
}
auto first_menu()
{
auto return_menu = first_menu; // Set to itself for 'auto', but I don't want to have to do this
std::cout << "2 or 3? ";
unsigned input = 0;
std::cin >> input;
switch (input)
{
case 2:
return_menu = second_menu;
break;
case 3:
return_menu = third_menu;
break;
default:
break;
}
return return_menu;
}
I like using auto for trivial types, but I don't really like relying on it because I don't know how to address the type I'm wanting, which is why I'm wondering what auto actually is here and how to explicitly declare the variables and function return types (probably using type aliases since that's most sensible).
Something to note:
All functions that FunctionDispath() can call take no parameters and return function pointers to other functions that take in no parameters and return the same type of function pointers.
I'd prefer an answer that explains both what the full type would be with no type aliases and how to use a type alias here.
First off, cool! This reminds me of middleware frameworks, or coroutines with tasks and event loops.
Doing this with straight-up function pointers will result in an infinitely recursive type, as many have mentioned. But if each task is a callable object, then you don't need recursive types as a forward reference will do. You can inherit std::function to make it easy:
struct task : std::function<task()> {
using std::function<task()>::function;
};
Then you can assign functions to it. You can also bind arguments with std::bind, or even use the default constructor to make an empty function with no target:
task n_hellos(int count) {
if (count) {
std::cout << "hello\n";
return std::bind(n_hellos, count-1);
}
return task();
}
You can cast an std::function to bool to see if it is empty, allowing for a terminal case. The event loop below quits when the next task is empty:
int main() {
task current_task = std::bind(n_hellos, 5);
while (current_task) {
current_task = current_task();
}
} // prints "hello" five times
Demo: https://godbolt.org/z/dHaSWC
I'm using some (somewhat C-ish) library which involves a callback mechanism. The callback functions I can provide it take a void* as a parameter so you can pass arbitrary stuff to them. For the sake of this question let's assume the lambda doesn't take any parameters, but it does capture stuff.
Now, I need to have my callback function invoke a lambda - and it must get this lambda somehow via the void *, i.e. we have
void my_callback(void * arbitrary_stuff) {
/* magic... and somehow the lambda passed */
/* through `arbitrary_stuff` is invoked. */
}
// ...
template <T>
void adapted_add_callback(MagicTypeInvolvingT actual_callback) {
/* more magic */
libFooAddCallback(my_callback, something_based_on_actual_callback);
}
// ...
void baz();
void bar() {
int x;
adapted_add_callback([x]() { /* do something with x */ });
adapted_add_callback(baz);
}
and I want to know what to replace magic, more_magic and MagicTypeInvolvingT with.
Other than the typing challenge here, what I'm worried about, obviously, is how to make sure the data the lambda encapsulates is available on the stack for eventual use, as otherwise I should probably get some kind of segmentation fault.
Notes:
my_callback() should be synchronous, in the sense that it'll execute the lambda on whatever thread it is on and return when it returns. It's either the fooLibrary or the lambda itself which do asynchronicity.
the most straightforward way might be ( assuming the C function is guaranteed to invoke the callback exactly once, and that the lambda is valid at callback point )
void my_callback(void * arbitrary_stuff) {
(*std::unique_ptr{ static_cast<std::function<void()>*>(arbitrary_stuff) })();
}
void adapted_add_callback( std::function<void()> actual_callback ) {
libFooAddCallback(my_callback, new auto( std::move(actual_callback) ) );
}
if you don't want the function<> overhead you'll need to implement your own type erasure ...
You have a couple of issues here.
One is that you can't depend on passing the lambda itself as a void *, so you'll pretty much need to pass a pointer to the lambda (well, the closure created from the lambda, if you want to be precise). That means you'll need to ensure that the lambda remains valid until the callback completes.
The second is a question about how those captures happen - capture by value, or by reference? If you capture by value, everything's fine. If you capture by reference, you also need to ensure that anything you've captured remains valid until the callback completes. If you capture a global by reference, that should normally be fine--but if you capture a local by reference, then the local (even potentially) goes out of scope before the lambda is invoked, using the reference will cause undefined behavior.
I went in a way similar to Massimiliano Janes', but without the overhead of std::function. You have to ensure that the callback is called only once by the library.
using Callback = void(*)(void*);
// Probes the type of the argument and generates a suitable cast & invoke stub
// Caution: self-destructs after use!
template <class F>
Callback cbkWrap(F &) {
return [](void *data) {
std::unique_ptr<F> retrieved(static_cast<F*>(data));
(*retrieved)();
};
}
// Moves the functor into a dynamically-allocated one
template <class F>
void *cbkFunc(F &f) {
return new F{std::move(f)};
}
int main() {
int x = 42;
auto lambda = [&x] { std::cout << x << '\n'; };
libFooAddCallback(cbkWrap(lambda), cbkFunc(lambda));
}
See it live on Coliru
If you can ensure that the lambda outlives the potential calls, you can get rid of the dynamic memory allocations and simply pas a pointer to it as data:
// Probes the type of the argument and generates a suitable cast & invoke stub
template <class F>
Callback cbkWrap(F &) {
return [](void *data) {
auto retrieved = static_cast<F*>(data);
(*retrieved)();
};
}
int main() {
int x = 42;
auto lambda = [&x] { std::cout << x << '\n'; };
libFooAddCallback(cbkWrap(lambda), &lambda);
}
See it live on Coliru
There is unfortunately no way to give ownership of the lamba to the library without knowing exactly how many times it will be called.
I'm having a small problem which I can't wrap my head around.
I have a function that looks like this:
template <typename T>
std::unique_ptr<Environment>& CreateEnvironment(sf::Vector2f& _position, bool _addToStatic = false);
This is my function pointer typedef
typedef std::unique_ptr<Environment>& (WorldEditor::*CreateEnvironmentPtr)(sf::Vector2f&, bool);
std::map<std::string,CreateEnvironmentPtr> listEnv;
And I'm trying to simply do this:
listEnv["test"] = &CreateEnvironment<Coin>(sf::Vector2f(200,200), false);
And i get the following error:
error C2440: '=' : cannot convert from 'std::unique_ptr<_Ty> *' to
'std::unique_ptr<_Ty> &(__thiscall WorldEditor::* )(sf::Vector2f
&,bool)'
I understand what the error is saying, but I don't know how to solve it. Also why does it even care about the return type when I'm pointing to the address of the function?
Best regards
nilo
problems such as these are often much better solved with std::function
std::map<std::string, std::function<void()> listEnv;
listEnv.emplace("test", [] {
CreateEnvironment<Coin>(sf::Vector2f(200,200), false);
});
to call:
listEnv.at("test")->second();
Based on your post I am not sure if you are attempting to create the member function pointer and map inside the CreateEnvironment class or outside of it, so I'll solve what I think is the more difficult problem of pointer to a separate object's member function.
I simplified your classes like so:
Environment
struct Environment
{
int i = 1;
};
Coin
struct Coin
{
int k = 0;
};
WorldEditor
struct WorldEditor
{
template <typename T>
std::unique_ptr<Environment> CreateEnvironment(int& _j, bool _addToStatic = false)
{
return std::make_unique<Environment>();
}
};
Solution: Map an object's member fn pointer, and then call it later
(I will be using C++11/14 syntax in my answer)
//declare a pointer to member function in WorldEditor
using CreateEnvironmentPtr = std::unique_ptr<Environment> (WorldEditor::*)(int&, bool);
//declare an object of type WorldEditor, because member function pointers need a "this" pointer
WorldEditor myWorldEditor;
int myInt = 42;
//map a string to the CreateEnvironment<Coin> function
std::map<std::string, CreateEnvironmentPtr> listEnv;
listEnv["test"] = &WorldEditor::CreateEnvironment<Coin>;
// call the member function pointer using the instance I created, as well as
// the mapped function
(myWorldEditor.*listEnv["test"])(myInt, false);
// (printing member value to cout to show it worked)
std::cout << (myWorldEditor.*listEnv["test"])(myInt, false)->i << std::endl; // prints 1
Live Demo
Solution 2: use std::bind and std::function
Perhaps we already know the parameters to the member function call at the time we create the entry for map. Using std::bind with a std::function will help us achieve that (Similar to Richard Hodges' solution):
// now our "function pointer" is really just a std::function that takes no arguments
using CreateEnvironmentPtr = std::function<std::unique_ptr<Environment>(void)>;
//declare an object of type WorldEditor, because member function pointers need a "this" pointer
WorldEditor myWorldEditor;
int myInt = 42;
//map a string to that function pointer
//ensure it gets called with the right args
// by using std::bind (which will also make the arg list appear the be void at call time)
// note that std::bind needs an instance of the class immediately after
// listing the function it should be binding
// only afterwards will we then pass the int& and bool
std::map<std::string, CreateEnvironmentPtr> listEnv;
listEnv["test"] = std::bind(&WorldEditor::CreateEnvironment<Coin>, &myWorldEditor, myInt, false);
// the mapped function
listEnv["test"]()->i;
// (printing resulting unique_ptr<Environment>'s member to cout to show it worked)
std::cout << listEnv["test"]()->i << std::endl; // prints 1
Live Demo 2
Suppose I want to implement a simple abstraction over pthreads.
(or any C API that takes function pointers for callbacks or threads).
Like std::thread, I want the interface to be able to take function objects in general.
How do I bridge the gap in a way that works for all cases?
(That includes binds, lambda functions, etc.)
I know about the std::function::target but afaik, it does not do what I need.
If the API takes functions with a void* for user data as, e.g., pthread_create() does, you'd pass a pointer to the function as user data, call a trampoline which casts the user data to your function type, and calls the function. For example:
#include <functional>
#include <pthread.h>
extern "C" void* trampoline(void* userData) {
return (*static_cast<std::function<void*()>*>(userData))();
}
void* start() {
// ...
return 0;
}
int main() {
pthread_t thread;
std::function<void*()> entry(start);
pthread_create(&thread, 0, &trampoline, &entry);
// ...
}
The immediate implication is, however, that the function object life-time isn't easily controlled. In the example above the std::function<void*()> object happens to live long enough but it isn't always as easy.
If the function you try to call doesn't have a user data argument, you are pretty much out of luck. You might get away with using global objects but it is almost certainly a rather fragile approach.
A lambda function can be used anywhere that takes regular function pointers. In other words, it can be used wherever you would use regular functions/pointers to functions..
Example: https://ideone.com/4CJjlL
#include <iostream>
void voidfunc(void (*func_ptr)(void))
{
func_ptr();
}
void funcwithargs(void (*func_ptr)(int, char, std::string), int a, char b, std::string c)
{
func_ptr(a, b, c);
}
int main()
{
auto vf = []{std::cout<<"Called void func..\n";};
auto vfwa = [](int a, char b, std::string c) {std::cout<<"Called func with args with: "<<a<<b<<" "<<c<<"\n";};
voidfunc(vf);
funcwithargs(vfwa, 10, 'x', " + 3");
return 0;
}
Likewise, you can use std::function instead of the function pointer..