I have a stack with threads using Boost. I have 2 classes with method run, for example:
class class1 {
public:
class1::class1(){
void run() { //I need to call getA
}
}
};
class class2 {
private:
float A;
public:
class2:class2() { A = 0; }
void run() { A++; }
float getA() { return A; }
};
In the main function, I have both run's methods as threads:
void main(){
class1 c1;
class2 c2;
boost::thread t1(&class1::run,c1);
boost::thread t1(&class2::run,c2);
t1.join();
t2.join();
}
I've unsucesfully tried using a mutex. I've also created a pointer of c2 into c1, but the value is not updated.
How could one class call a method in another class when their instances are in different threads?
Firstly, some clarifications:
Classes are not objects in C++, they are mere compile-time constructs to group related stuff. So, "how could one class" should rather be "how could one instance" or "one class".
Further, "when their instances are in different threads" doesn't make sense either, because threads (as opposed to processes) share the same memory space. However, you still need to reach the other object, for which you need a reference, which you somehow need to pass along.
Lastly, to "Call [a] Method in other Boost Thread" is ambiguous. It could mean you want to invoke a method on a different object, which would be called by the same thread though. It could also mean that you want a different thread to call the method and then return the result to your thread, which is way more complicated. That would require some form of communication with that other thread.
Now, in order to get objects passed to a thread function, check out e.g. Boost.Bind. Since it doesn't matter that these things are called in a thread, you could also pass a reference to the class2 instance to the ctor of class1 and store it there. Much of that depends on what you actually want. However, one note still: If you share objects between threads, you will have to sync access to them somehow, e.g. using a mutex.
PS: C++11 has its own threads which I would prefer over Boost.Thread. They are mostly the same, but one of them is standard, while Boost still is an addon.
Related
There's some code at my company that takes the following form:
class ObjectA {
public:
ObjectA(ObjectB &objectB): objectB(objectB) { }
void Initialize() { ... }
private:
ObjectB &objectB;
};
class ObjectB {
public:
ObjectB(ObjectA &objectA): objectA(objectA) { }
void Initialize() { ... }
private:
ObjectA &objectA;
};
Basically, two classes have a mutual dependency on the other.
This in itself isn't what bothers me, (although it's not great design IMO), it's that the mutual dependencies are passed through the constructor by reference in both situations.
So, the only way to actually construct this pair of objects (they are both required in the application) is to pass an incomplete reference as a dependency. To account for this, the separate Initialize methods are added as a 2nd stage constructor which are then called after both objects are created. Consequently, the constructors often times do nothing except assign the constructor parameters to the object internals, and initialize everything in the Intizialize method.
Although the code may be valid, my inclination is that this is a fundamentally flawed design for the following reasons:
The state of a dependent object can't be guaranteed in the
constructor
It requires the developers to make an additional call to Initialize
It precludes the use of compiler warnings that check if member variables have been initialized
There's nothing preventing Initialize from being called multiple times, which can result in strange, hard to track down errors
My coworkers tell me that having a separate initialize method simplifies the object construction since the developer doesn't have to worry about what order objects are declared in the application root. They can be declared and constructed in completely arbitrary order since everything is guaranteed to be valid once Initialize gets called.
I've been advocating that object construction should follow the same order of the dependency graph and that these objects should be redesigned to remove the mutual dependency, but I wanted to see what the SO gurus had to say about it. Am I wrong to think this is bad practice?
Edit:
The way these classes actually get constructed is through a factory class like below:
Factory {
public:
Factory():
objectA(objectB),
objectB(objectA) {
}
private:
ObjectA objectA;
ObjectB objectB;
};
This is bad practice yes. Passing a reference to objectB for objectA to work with while it's not properly initialized yet is a no-no.
It might be standard compliant and safe code now because ObjectA doesn't try to access the passed reference to ObjectB in its constructor but that safety is hanging by a thread. If later on someone decides to just initialize in the constructor or access anything from objectB, or change it any other way where objectB will be used you end up with UB.
This sounds like a use case for pointers that are reseated after both constructors have run.
I too don't like the code as posted - it is unnecessarily complicated and fragile. There is usually some concept of ownership when two classes cooperate like this, so, if objects of type A own objects of type B (which they probably should), then you would do something like:
#include <memory>
class A;
class B
{
public:
B (A& a) : a (a) { }
private:
A& a;
};
class A
{
public:
A () { b = std::make_unique <B> (*this); }
private:
std::unique_ptr <B> b;
};
Live demo
I just had to put in a fix for a difficult-to-find error, but I am not happy about the fix. Our application is C++ running in Windows, and the error was a pure virtual call crash. Here is some background:
class Observable
{
public:
Observable();
virtual ~Observable();
void Attach(Observer&); // Seize lock, then add Observer to the list
void Detach(Observer&); // Seize lock, then remove Observer from the list
void Notify(); // Seize lock, then iterate list and call Update() on each Observer
protected:
// List of attached observers
};
class Subject : public Observable
{
// Just important to know there is a subclass of Observable
}
class Observer
{
public:
Observer();
virtual ~Observer(); // Detaches itself from the Observable
void Update() = 0;
};
class Thing : public Observer
{
public:
void Update(); // What it does is immaterial to this question
};
Because this is a multi-threaded environment, there are locks in place for Attach(), Detach(), and Notify(). Notify() seizes the lock and then iterates the list of observers and calls Update() on each one.
(I hope this is enough of a background without having to post the complete body of code.)
The problem arose when an observer was being destroyed. On destruction, the Observer detaches itself from the Observable. At the same time, in another thread, Notify() is being called on the Subject. My original thought was that we were protected because of the locks in Detach() (called on destruction of the Observer), and Notify(). However, C++ destroys the subclass first, then the base class. This meant that, before the lock in Detach() was obtained which would have prevented the Notify() function from continuing, the implementation of the pure virtual Update() function was destroyed. The Notify() function continued (because it had already obtained the lock) and attempted to call Update(). The result is a crash.
Now, here is my solution, which works, but gives me a queasy feeling. I changed the Update() function from being pure virtual to just being virtual and provided a body that did nothing. The reason this bothers me is that Update() is still being called, but on a partially destructed object. In other words, I am getting away with something, but I am not wild about the implementation.
Other options discussed:
1) Move the locking into the subclasses. Not desirable because it forces the developer of each subclass to duplicate the logic. And if he omits the locking, bad things can happen.
2) Force the destruction of the observer to occur via a Destroy() function. Honestly, I wasn't sure how to implement this for stack-based objects.
3) Have the subclass call a "PreDestroy()" function in its destructor to notify the base class that destruction is imminent. I wouldn't know how to force this, and forgetting it could lead to hard-to-find runtime errors.
Can anyone offer any suggestions as to a better way to protect against these types of crashes? I have this unpleasant feeling that I am missing the elephant in the room.
JAB
This problem is an illustration of a more general consequence of multi-threaded design: no object that is affected by multiple threads can provide a guarantee of no concurrent access to itself at any point in time. This consequence is the elephant in the room that is giving you the unpleasant feeling you describe at the end of your question.
In short, your problem is that Attach(), Detach(), and Notify() are responsible for both grabbing the appropriate lock and doing their thing. They need to be able to assume the lock is grabbed before they are called.
Unfortunately, the solution requires a more complicated design. It is necessary for some single source that is independent of your objects (or classes) to mediate the construction, updating (including attaching and detaching), and destruction of all your objects. And it is necessary to prevent any of those processes from occurring independently of the mediator.
It is a design choice whether you prevent those processes by technical means (e.g. access control, etc) or simply state policies that all your types must comply with. That choice depends on whether you can rely on your developers (including yourself) to follow policy guidelines.
About your solutions:
Not good, because of the reasons you give.
Ok. Additionally, define ~Observer() as protected (as any other destructor of derived classes) to avoid calling delete directly and write a member void Destroy(). The problem is that it will not work for automatic (local) variables. Actually, with a protected destructor you will not be able to declare local variables.
You probably mean calling PreDestroy() from the destructor of each subclass destructor. The problem will be not to forget it (you can assert that it has been called from ~Observer()) and if you have several levels of inheritance.
About your original solution:
Making Update() a callable virtual function seems to work, but it is technically wrong. While one thread is calling the virtual Update(), using the vtable pointer, another thread is calling ~Thing() and updating the vtable pointer to that of Observer(). The first thread holds the lock, but the second one does not, so you have a race.
My advice would be use option 2 unless you are very fond of automatic instances of subclasses of Observer.
If you are willing, you could try with templates:
template<typename O>
class ObserverPtr : Observer
{
public:
ObserverPtr(O *obj)
:m_obj(obj)
{}
void Update()
{
m_obj->Update();
}
~ObserverPtr()
{
PreDestroy();
delete m_obj;
}
private:
O *m_obj;
};
And then Thing will not derive from Observer.
You can also create alternative variants of this template:
to hold a reference to the real observer instead of a pointer (O &m_obj;). No use of delete.
to define the real observer as an actual member (O m_obj;). No dynamic allocations.
to hold a smart pointer to the real observer.
I think that unless you mandate to call Detach from the derived class destructor, it will not have an easy solution.
One solution which comes into my mind might be to utilize an extra "wrapper" which will take care of de-registration (and might actually do the registration as well).
Something like this (for example):
class ObserverAgent;
// the wrapper class - not virtual
class Observer
{
public:
Observer(Observable &subject, ObserverAgent &agent)
: _subject(subject), _agent(agent)
{
_subject.Attach(*this);
}
~Observer()
{
_subject.Detach(*this);
}
void Update()
{
_agent.Update();
}
private:
Observable &_subject;
ObserverAgent &_agent;
};
// the actual observer polymorphic object
class ObserverAgent
{
public:
ObserverAgent();
virtual ~ObserverAgent();
protected:
// only callable by the Observer wrapper
friend class Observer;
virtual void Update() = 0;
};
class Thing : public ObserverAgent
{
public:
virtual void Update();
};
The use is then indeed more convoluted:
Subject s;
{ // some scope
Thing t;
Observer o(s, t);
// do stuff
} // here first Observer is detached and destroyed, then Thing (already unregistered)
Note that you cannot Attach/Detach Thing (ObserverAgent) directly, only through Observer (because Observable takes the Observer, not the ObserverAgent).
Perhaps it could be possible to wrap it in a single class for simpler use (Agent being an inner class of the Observer), however then there might be problems with the lifetime of the agents (as the destruction of the Observer would have to be virtual again).
Why not expose the lock as protected in Observable? Observable::~Observable acquires the lock if it's not acquired already by this thread, then goes on with the cleanup. Meanwhile EVERY subclass of Observable acquires the lock in its dtor without further releasing it (which is only done in ~Observable itself).
Frankly, in this design the simplest and the most consistent solution seems to manually Detach() each Observer at the very start of the most derived class' destructor. I don't see how this can be automated, and since something has to be done at the dawn of destruction, why not detachment.
...Well, if we don't need to go deeper:
template<class Substance> struct Observer {
Observer(Observable &o): o(o) { o.attach(s); }
~Observer() { o.detach(s); }
Substance &subst() const { return s; }
private:
Observable &o;
Substance s;
};
struct ThingSubst { void update(); long stats(); };
typedef Observer<ThingSubst> Thing;
Observable o;
Thing thing(o);
std::cout << thing.subst().stats() << std::endl;
I have not been able to determine where a strange crash is coming from, but the fact it's not happening deterministically makes me suspect threading.
I have something like this:
class MyClass
{
MyClass() : mExit(false), mThread(&MyClass::ThreadMain,this)
{}
void ThreadMain()
{
unique_lock<mutex> lock(mMutex);
mCondition.wait(lock, [&] { return mExit; });
}
std::thread mThread;
std::mutex mMutex;
std::condition_variable mCondition;
bool mExit;
};
Obviously this is very simplified but I don't know for sure where the crash is happening yet so I want to ask if this setup can cause issues? What order is everything initialised for instance - is there a possibility ThreadMain can run before an instance of the class is fully constructed for example?
It looks like some examples I've seen online but I am not certain enough to say it's definitely safe or not.
The only issue I see is that class members are initialized in the order they are declared in the class. Since mThread comes before all of the other class members it could be possible that the thread is using them before they are ever initialized.
To fix this you can rearrange the class members but I do not like this approach. If someone else comes along and changes the order it could break the code. You should be able to let the thread get default initialized and then start the thread in the constructor body because at that point all class members have been initialized.
In addition to the member-construction-order-vs-thread-early-execution issue described by #NathanOliver, I would like to point out that the code will still exhibit undefined behaviour when using a virtual fuction in the place of ThreadMain.
Using a virtual function with your design is a problem as virtual functions are looked up from the vtable, and the pointer to the vtable isn't initialized until the constructor block has finished executing. Thus you end up with a thread that uses a pointer to a function that isn't initialized yet, which is UB.
The general solution to this kind of RAII thread-handler problem is to separate the initialization of the object from the execution of the thread, e.g., using a start function. This will also remove the dependency on the construction order of the members.
struct MyClass {
MyClass() : mExit(false) {}
void start() { mThread = std::thread{&ThreadMain, this}; } // Start function.
virtual void ThreadMain() = 0;
std::atomic<bool> mExit; // Not even bool is atomic :)
std::mutex mMutex;
std::condition_variable mCondition;
std::thread mThread;
};
This ensures that MyClass is constructed when starting the thread. Now, it is also possible to use polymorphism.
struct Derived : public MyClass {
virtual void ThreadMain() {
std::unique_lock<std::mutex> lock(mMutex);
mCondition.wait(lock, [&] { return mExit.load(); });
}
};
However, now the thread must be started using two statements instead of one, e.g., MyClass m; m.start();. To get around this we can simply create a wrapper class that executes the start function in the constructor body.
struct ThreadHandler {
ThreadHandler() { d.start(); }
Derived d;
};
Yes it could have bad behaviour since mThread may be started while the MyClass instance is not yet constructed.
My thumb rule: if I have to use this in the constructor, I doing something naughty ;).
My question in code:
I have a class A, which has a private member b of class B, like:
class A
{
public:
A();
~A();
private:
B b;
};
class B
{
public:
B();
~B();
int getMemberOfB() {return m_memberOfB;}
private:
int m_memberOfB;
};
Is there any way to observe the m_memberOfB in an object of A, if m_memberOfB changes? (like signal & slot mechanism in qt) Because b is a member of class A, the callback may should also not work, does it? Acctually I want to get the current value of m_memberOfB in an object of A, if m_memberOfB is changed. Any idea ? Thanks a lot!
EDIT: I'm new to callback. If callback can work, I want to set a member function of class A as a callback, which can be called by B. But in order to call the callback function, there should be an object of A, which can call the callback. How can I get an instance of A in b ? Or rather set the callback as global function? Could anyone give me a small example ? Thanks very much !
First off, you probably want to make B::m_memberOfB a static; otherwise, you will have a different instance of it for every instance of a B class which would mean you would know when it changes because you would be changing it from your A object.
After that, you need to put the problem into context. There are loads of signalling mechanisms in C/C++, it all depends on what you are dealing with.
For example, when you are dealing with threads,you could use mutexes and/or semaphores and for inter-process signalling you have pipes or signals.
You can even use message queues.
Let's assume you only have one thread (main) and you want to achieve what you just said - you would have to use polling, whether you manually check the value to see if it changed, or use a mutex that will be release only when the value changes is up to you, but you are still polling.
I'm trying to pass a virtual method to the thread class' constructor (C++ thread).
After searching all over, I've only been able to pass a non-virtual member method.
My base class A has a start method as follows:
void A::start() {
thread(&A::runnable,A()); // <--- What do I change here?
}
The function runnable is virtual and is also implemented in derived class B.
I override runnable in derived class B.
I then invoke start on B.
Obviously, and undesirably, the start function uses runnable implemented in A (instead of B) because it is explicitly defined in A::start.
Is there any way to let the runnable function be dynamically bound?
I thought of using templates and a couple of other creative solutions. (I eventually will implement start in B if there are no real solutions)
Any help would be greatly appreciated.
Obviously, and undesirably, the start function uses runnable implemented in A (instead of B) because it is explicitly defined in A::start.
This could be obvious to you, but it is incorrect. When you create a thread you pass an unnamed temporary instance of class A, which obviously has type A so A::runnable would be always called, but you should pass this:
void A::start() {
thread(&A::runnable,this); // <--- What do I change here?
}
Then proper virtual function would be called.
See Boost::Bind and virtual function overloads: why do they work? for details why.
There are a couple of things to address.
First in A::start() you create an anonymous local thread object. Unfortunately, this object will be destructed as soon as you leave A::start(). This will trigger an abort.
When you create a thread object you must always either join() it or detach() it before the object gets destructed.
For the rest of the answer, I'll use a private thread t in A:
class A {
...
protected:
thread t; // default constructed thread object, i.e. without associated thread of execution
public:
...
~A() {
if (t.joinable()) // If thread active and not detached, be sure that it's joined before it is destructed !!
t.join();
}
....
};
Next, in your thread creation, you use A() as parameter. This means that you will create a new anonymous A object and pass it as argument. I guess it's not what you intend to do, so you use this instead.
Then, as was told by Slava, when &A::runnable is used in combination with this, it is the virtual function that is called. So start() should look like:
void start() {
t = move (thread (&A::runnable, this )) ; // Here I create an anonymous thread and move it to t.
}
If your run this code, you'll notice that A::runnable() is called for class A objects and B::runnable() for class B objects.