Start thread with derived class's member function - c++

Similar to this question: Start thread with member function and this one: std::thread calling method of class
However I have the following:
#include <thread>
#include <iostream>
class myAbstractClass {
public:
virtual void myFunction() = 0;//abstract class
}
class myFirstClass : public myAbstractClass {
public:
void myFunction() { std::cout << "First class here";}
}
class mySecondClass : public myAbstractClass {
public:
void myFunction() { std::cout << "Second class here";}
}
Then I have to call myFunction() from a different place in a new thread, but the following does not compile (and I can't think of anything else to try):
public void callMemberFunctionInThread(myAbstractClass& myInstance) {
std::thread myThread (&myAbstractClass::myFunction, myInstance);
//supposed to call myInstance.myFunction() on myThread
}

Pass std::ref(myInstance). Note that std::thread constructor will make a copy of the arguments passed to it (see here), and you can't copy a myAbstractClass.
(Then, all of this will still work because std::thread functionality is described in terms of std::invoke, which unwraps the std::reference_wrapper obtained by std::ref and calls the pointer to member function onto it. See here).

Related

Can't start C++ std::thread with callable as argument

I would like to have the following class setup in a program:
A class that implements a buffer. This buffer, when full, would spawn a thread that makes a callback to handle what to do with the full buffer.
A class that includes a buffer object. Implements the callback function.
I'm having some trouble spawning the std::thread that runs the callback. It seems like I'm getting its parameters wrong, but I can't figure it out.
The minimal reproducible example:
#include <thread>
class MyClass;
class CallbackClass
{
public:
void (MyClass::*callback)();
std::thread a_thread;
void setCallback(void (MyClass::*cb)())
{
callback = cb;
}
void writeCall()
{
a_thread = std::thread(callback); // error here
}
};
class MyClass
{
public:
CallbackClass callbackobject;
MyClass()
{
callbackobject.setCallback(&MyClass::bufferWriter);
}
void bufferWriter(){}
};
int main(){}
The compiler error I get:
error: no matching function for call to ‘std::thread::_Invoker<std::tuple<void (MyClass::*)()> >::_M_invoke(std::thread::_Invoker<std::tuple<void (MyClass::*)()> >::_Indices)’
operator()()
on this line:
a_thread = std::thread(callback); // error here
void (MyClass::*callback)();
This is a pointer to a class method.
a_thread = std::thread(callback);
A class method is not a function that can be called by itself. The class method requires an object for which it gets invoked. You need to store, or obtain a pointer to a MyClass object, from somewhere. For example, you can pass a 2nd parameter to `setCallback:
void setCallback(void (MyClass::*cb)(), MyClass *ptr)
and then stash it away, somewhere, then use it to invoke the class method. Typically, this would be something like:
a_thread = std::thread(callback, ptr);

Is there a way to reference the class of the current object

I'm making a class which has a method that launches some threads of member functions in the same class. I'm quite new to threads in c++, especially when classes are involved but this is what iv'e come up with.
class A
{
public:
void StartThreads()
{
std::thread fooThread(&A::FooFunc, this);
fooThread.join();
}
protected:
virtual void FooFunc()
{
while (true)
std::cout << "hello\n";
}
};
My question is, if i can get the name of the current object, because now if i create a class B which inherits from A but overwrites FooFunc, FooFunc from class A will be called when i do:
B b;
b.StartThreads();
So i'm looking for a way to replace std::thread fooThread(&A::FooFunc, this) with something like std::thread fooThread(&this->GetClass()::FooFunc, this). I could just make StartThreads virtual and overwrite it in derived classes, but It would be better just to write it once and being done with it. Is there a way to do this or something that results in the same thing?
In case of that your this is known at compile-time then static metaprogramming to the rescue.
C++, Swift and Rust (and now Scala also) are static languages that has a lot of compile time tricks to do for problems like that.
How? In your case templates could help you.
Also, you don't need it to be a member function, it can be a friend function (so that you can easily use templates).
class A
{
public:
template<typename T>
friend void StartThreads(const T& obj);
protected:
virtual void FooFunc()
{
while (true)
std::cout << "hello\n";
}
};
template<typename T>
void StartThreads(const T& obj) {
std::thread fooThread(&T::FooFunc, obj);
fooThread.join();
}
WARNING: This ONLY works if the class is known at compile time, i.e.
class B: public A {
};
...
B b;
A &a = b;
StartThreads(a); // Will call it AS IF IT IS A, NOT B
Another solution:
Functional programming to the rescue, you can use lambdas (or functors using structs if you are on C++ prior to C++11)
C++11:
void StartThreads()
{
std::thread fooThread([=](){ this->FooFunc(); });
fooThread.join();
}
C++98:
// Forward declaration
class A;
// The functor class (the functor is an object that is callable (i.e. has the operator (), which is the call operator overloaded))
struct ThreadContainer {
private:
A &f;
public:
ThreadContainer(A &f): f(f) {}
void operator() ();
};
class A
{
public:
// To allow access of the protected FooFunc function
friend void ThreadContainer::operator() ();
void StartThreads()
{
// Create the functor
ThreadContainer a(*this);
// Start the thread with the "call" operator, the implementation of the constructor tries to "call" the operand, which here is a
std::thread fooThread(a);
fooThread.join();
}
protected:
virtual void FooFunc()
{
while (true)
std::cout << "hello\n";
}
};
class B: public A {
protected:
virtual void FooFunc() {
while(true)
std::cout << "overridden\n";
}
};
void ThreadContainer::operator() () {
f.FooFunc();
}
You've looked at using a virtual FooFunc() directly, and somehow surmised that it doesn't work. (I won't address the accuracy of that here, as that is being brought up in the question's comments.) You don't like the idea of moving the virtual function earlier in the process. So why not move it later? There is a somewhat-common paradigm out there that uses non-virtual wrappers to virtual functions. (Usually the wrapper is public while the virtual function is protected or private.) So, something like:
class A
{
public:
void StartThreads()
{
std::thread fooThread(&A::FooFuncCaller, this); // <-- call the new function
fooThread.join();
}
protected:
void FooFuncCaller() // <-- new function layer
{
FooFunc();
}
virtual void FooFunc()
{
while (true)
std::cout << "hello\n";
}
};
Of course, if the direct call to the virtual Foofunc works, might as well use that. Still, this is simpler than using templates or custom functor classes. A lambda is a reasonable alternative, with the benefit of not changing your class' interface (header file).
Thanks for all of your answers, it turned out that my question was unrelated and that i messed up some other members in the class.
Thanks for your answers giving me some insight into other ways you can do the same thing using different methods. (https://stackoverflow.com/users/9335240/user9335240)

Guarding against vtable data race in derived destructor

Suppose I have the following code
#include <thread>
#include <iostream>
#include <atomic>
struct FooBase {
void start(){
run_condition_ = true;
t_ = std::thread([this](){
thread_handler();
});
}
virtual ~FooBase(){
run_condition_ = false;
if(t_.joinable())
t_.join();
}
protected:
virtual void thread_handler() = 0;
std::atomic_bool run_condition_{false};
private:
std::thread t_;
};
struct Foo : FooBase {
void thread_handler() override {
while(run_condition_){
std::cout << "Foo derived thread.." << std::endl;
}
}
};
int main(){
Foo f;
f.start();
getchar();
return 0;
}
Here I think because the destructor of the derived class Foo is called before FooBase the thread_handler vtable lookup happens in the base class IF the thread has not yet joined (still running) when the destructor of Foo is done. Since FooBase::thread_handler is pure virtual I am essentially guranteed a sigabort.
How do I guard against this? I hack my way through by not having thread_handler as pure virtual
virtual void thread_handler(){}
But I am lost as to how I can guard against this in the baseclass itself, I can implement a join_thread interface in the base class and call this from every derived class, but this seems cumbersome.
There's two issues here, neither of which match precisely what you described.
Your thread only gets stopped in ~FooBase(). This means that if Foo::thread_handler ever reads or writes to any of its members, they will get destroyed out from under it before the thread is stopped.
It you get to the destructor fast enough, it's possible that start() won't have actually invoked thread_handler() on the new thread by the time Foo gets destroyed - which will lead to the pure virtual call.
Either way, you need to ensure that by the time Foo is destroyed, anything related to thread_handler is done. This implies that every derived class from FooBase has to have, in its destructor:
run_condition_ = false;
if (t_.joinable()) {
t_join();
}
Setting aside that this directly doesn't work because t_ is private (you could wrap that into a protected stop()), it's an awkward design if all of your derived classes need to do something special just to work. You could instead put FooBase into its own class that just takes an arbitrary callable as an argument:
class joining_thread {
public:
joining_thread() = default;
~joining_thread() { stop(); }
bool running() const { return run_condition_.load(); }
template <typename... Args>
void start(Args&&... args) {
run_condition_ = true;
t_ = std::thread(std::forward<Args>(args)...);
}
void stop() {
run_condition_ = false;
if (t_.joinable()) t_.join();
}
private:
std::thread t_;
std::atomic_bool run_condition_{false};
};
And then your Foo can just have that as a member:
class Foo {
public:
void start() {
t_.start([this]{
while (t_.running()) { ... }
});
}
private:
// just make me the last member, so it's destroyed first
joining_thread t_;
};
That's still a little awkward with the whole running() thing, but hopefully the idea makes sense.
What you describe is not possible. You call "start" after you have constructed the object. The object is at that stage valid. You have avoided the common problem of calling a virtual function in the constructor, which would have caused issues. There is something called a memory barrier that is implied by any thread calls, so you can count on the fact the new thread will start with a view of memory that existed at the point it was created. Any thing that existed AND was not changed, is fine.
Your problem (as described in another answer) is that you can exit and destroy the object (and it's vtable), before the thread is complete.
The simplest fix for this is use a packaged task. Calling "get" on the future ensures the task is finished before you continue. Consider the code below
#include "stdafx.h"
#include <thread>
#include <iostream>
#include <atomic>
#include <future>
int main()
{
std::atomic<bool> stop{ false };
std::future<void> sync;
std::packaged_task<void()> task([&stop]()
{
while (!stop)
{
std::cout << "Running\n";
}
});
std::thread thread([&task]() {task();});
getchar();
stop = true;
task.get_future().get();
thread.join();
return 0;
}

c++ , pthread and static callbacks. "this" returns a pointer to the base class inctead of the derived one [duplicate]

This question already has an answer here:
c++ , pthread and static callbacks. "this" returns a pointer to the base class inctead of the derived one (part 2)
(1 answer)
Closed 7 years ago.
I am using as basis this cpp thread class. This I use as a base class for threads. Note that in my case Thread::main() is a virtual function (unlike in the link). So I basically use:
class Thread {
public:
virtual void main()
{
cout << "This should not be run once derived and redefined." << endl;
}
void run()
{
pthread_create(&thread, 0, &callback, this);
}
pthread_t thread;
}; // class Thread
void* callback(void* obj)
{
static_cast<Thread*>(obj)->main();
return(0);
} // callback
Then I create a derived class and re-define the myThreadedClass::main() member to actually do something meaningful.
Finally, I instantiate the myThreadedClass object from other classes or my main function call as follows:
main(int argc, char** argv){
myThreadedClass thr;
thr.run();
//do other stuff
}
This works fine; The callback function gets a pointer to the derived class instantiation, so the myThreadedClass::main() gets executed.
However, I now try to create a different derived class class otherThreadClass : public Thread. Again I re-define my otherThreadClass::main() , but now I have a member function in the derived class which (unlike before) calls Thread::run().
class otherThreadClass : public Thread{
public:
writeToDiskAsync(string& str){
prepareString(str);
//spawn a thread to carry the write without blocking execution
run();
}
};
in this case from my main function I do
main(int argc, char** argv){
otherThreadClass thr;
thr.writeToDiskAsync(aString);
//do other stuff
}
The problem in this case is that the callback function gets a pointer to the Thread class and the Thread::main() ends up being executed instead of the otherThreadClass::main().
I tried passing a pointer to the instantiated myThreadedClass object during instantiation (using initialisation lists and an altered call to Thread::run(void* instance)) as follows
//in main function
otherThreadClass thr(&thr);
//in class
otherThreadClass::otherThreadClass(otherThreadClass* ptr):instancePtr(ptr)
{}
otherThreadClass::writeToDiskAsync(string& str)
{
//do stuff
run(instancePtr);
}
//and finally
Thread::run(void* parentObj)
{
pthread_create(&thread, 0, &callback, parentObj);
}
but it does not work. And I think this is probably not a nice way to do it anyway. So what can I do to let the callback function get apointer to the derived class instance instead of the base class ?
thank you
If you will try to call a function using base class ptr , everytime base class version gets called as long as function is not virtual .
so simpler solution to your problem would be to make main virtual as below :
#include <iostream>
#include<pthread.h>
#include<unistd.h?
using namespace std;
void* callback(void* obj);
class Thread {
public:
virtual int main()
{
cout << "Hi there Base class" << endl;
return(0);
}
void run()
{
pthread_create(&thread, 0, &callback, this);
}
pthread_t thread;
};
class otherThreadClass : public Thread{
public:
virtual int main()
{
cout << "Hi there other class" << endl;
return(0);
}
void writeToDiskAsync(string str){
//spawn a thread to carry the write without blocking execution
run();
}
};
class Thread;
void* callback(void* obj)
{
static_cast<Thread*>(obj)->main();
return(0);
} // callback
int main() {
// your code goes here
otherThreadClass thr;
thr.writeToDiskAsync(string("aS"));
sleep(10);//it is neccessary as main thread can exit before .
return 0;
}
output : Hi there other class
Whereas if main is not virtual , it will always call base class version of main as you are calling through a base class ptr (static binding will happen )

c++ overriding a function only for a specific instance

I was wondering whether there's a way to override a function for a specific instance only. For ex,
class A
{
public:
...
void update();
...
}
int main()
{
...
A *first_instance = new A();
// I want this to have a specific update() function.
// ex. void update() { functionA(); functionB(); ... }
A *second_instance = new A();
// I want this to have a different update() function than the above one.
// ex. void update() { functionZ(); functionY(); ...}
A *third_instance = new A();
// ....so on.
...
}
Is there a way to achieve this?
I think virtual function is just what you want, with virtual function, different instances of the same type can have different functions, but you need to inherit the base class. for example
class A
{
public:
...
virtual void update()
{
std::cout << "Class A\n";
}
...
};
class B: public A
{
public:
virtual void update()
{
std::cout << "Class B\n";
}
};
class C: public A
{
public:
virtual void update()
{
std::cout << "Class C\n";
}
};
int main()
{
...
A *first_instance = new A();
// I want this to have a specific update() function.
// ex. void update() { functionA(); functionB(); ... }
A *second_instance = new B();
// I want this to have a different update() function than the above one.
// ex. void update() { functionZ(); functionY(); ...}
A *third_instance = new C();
// ....so on.
...
}
each instance in the above code will bind different update functions.
Besides, you can also use function pointer to implement your requirement, but it is not recommended. For example
class A
{
public:
A(void(*u)())
{
this->update = u;
}
...
void (*update)();
};
void a_update()
{
std::cout << "update A\n";
}
void b_update()
{
std::cout << "update B\n";
}
void c_update()
{
std::cout << "update C\n";
}
int main()
{
...
A first_instance(a_update);
// I want this to have a specific update() function.
// ex. void update() { functionA(); functionB(); ... }
A second_instance(b_update);
// I want this to have a different update() function than the above one.
// ex. void update() { functionZ(); functionY(); ...}
A third_instance(c_update);
// ....so on.
...
}
Hope helps!
Hold a function in the class.
#include <iostream>
#include <functional>
using namespace std;
class Foo
{
public:
Foo(const function<void ()>& f) : func(f)
{
}
void callFunc()
{
func();
}
private:
function<void ()> func;
};
void printFoo() { cout<<"foo"<<endl; }
void printBar() { cout<<"bar"<<endl; }
int main()
{
Foo a(printFoo);
Foo b(printBar);
a.callFunc();
b.callFunc();
}
You may have noticed that the end brace of a class is often followed by a semicolon, whereas the end braces of functions, while loops etc don't. There's a reason for this, which relates to a feature of struct in C. Because a class is almost identical to a struct, this feature exists for C++ classes too.
Basically, a struct in C may declare a named instance instead of (or as well as) a named "type" (scare quotes because a struct type in C isn't a valid type name in itself). A C++ class can therefore do the same thing, though AFAIK there may be severe limitations on what else that class can do.
I'm not in a position to check at the moment, and it's certainly not something I remember using, but that may mean you can declare a named class instance inheriting from a base class without giving it a class name. There will still be a derived type, but it will be anonymous.
If valid at all, it should look something like...
class : public baseclass // note - no derived class name
{
public:
virtual funcname ()
{
...
}
} instancename;
Personally, even if this is valid, I'd avoid using it for a number of reasons. For example, the lack of a class name means that it's not possible to define member functions separately. That means that the whole class declaration and definition must go where you want the instance declared - a lot of clutter to drop in the middle of a function, or even in a list of global variables.
With no class name, there's presumably no way to declare a constructor or destructor. And if you have non-default constructors from the base class, AFAIK there's no way to specify constructor parameters with this.
And as I said, I haven't checked this - that syntax may well be illegal as well as ugly.
Some more practical approaches to varying behaviour per-instance include...
Using dependency injection - e.g. providing a function pointer or class instance (or lambda) for some part of the behavior as a constructor parameter.
Using a template class - effectively compile-time dependency injection, with the dependency provided as a function parameter to the template.
I think it will be the best if you'll tell us why do you need to override a function for a specific instance.
But here's another approach: Strategy pattern.
Your class need a member that represent some behaviour. So you're creating some abstract class that will be an interface for different behaviours, then you'll implement different behaviours in subclasses of that abstract class. So you can choose those behaviours for any object at any time.
class A;//forward declaration
class Updater
{
public:
virtual ~Updater() {};//don't forget about virtual destructor, though it's not needed in this case of class containing only one function
virtual void update(A&) = 0;
}
class SomeUpdater
{
public:
virtual void update(A & a);//concrete realisation of an update() method
}
class A
{
private:
Updater mUpdater;
public:
explicit A(Updater updater);//constructor takes an updater, let's pretend we want to choose a behaviour once for a lifetime of an object - at creation
void update()
{
mUpdater.update(this);
}
}
You can use local classes, yet, personally, I consider the "hold function in the class" approach mentioned in the other answer better. I'd recommend the following approach only if doFunc must access internals of your base class, which is not possible from a function held in a member variable:
class ABase {
public:
void Func () { this->doFunc (); }
private:
virtual void doFunc () = 0;
public:
virtual ~ABase () { }
};
ABase* makeFirstA () {
class MyA : public ABase {
virtual void doFunc () { std::cout << "First A"; }
};
return new MyA;
}
ABase* makeSecondA () {
class MyA : public ABase {
virtual void doFunc () { std::cout << "Second A"; }
};
return new MyA;
}
int main () {
std::shared_ptr<ABase> first (makeFirstA ());
std::shared_ptr<ABase> second (makeSecondA ());
first->Func ();
second->Func ();
}
From a design patterns point of view, the "local classes" approach implements the template method pattern, while the "hold a function(al) in a member variable" approach reflects the strategy pattern. Which one is more appropriate depends on what you need to achieve.