When I build the following C++/CLI code in VS2008, a code analysis warning CA1001 is displayed.
ref class A
{
public:
A() { m_hwnd = new HWND; }
~A() { this->!A(); }
protected:
!A() { delete m_hwnd; }
HWND* m_hwnd;
};
ref class B
{
public:
B() { m_a = gcnew A(); }
protected:
A^ m_a;
};
warning: CA1001 : Microsoft.Design :
Implement IDisposable on 'B' because
it creates members of the following
IDisposable types: 'A'.
To resolve this warning, I would have to add this code to class B:
~B() { delete m_a; }
But I don't understand why. Class A implements IDisposable via its destructor (and finalizer).
So surely whenever A gets garbage-collected, then A's finalizer or destructor will get called, freeing its unmanaged resources.
Why does B have to add a destructor to call 'delete' on its A member?
Will the GC only call A's destructor if B explicitly calls "delete m_a"?
Edit: it seems this works automatically if you use the "syntax sugar" method of declaring the A member, like this:
ref class B
{
public:
B() { }
protected:
A m_a;
};
but this is not always possible.
Why isn't the GC clever enough to automatically dispose of the managed reference pointer of A^, once no one else has a pointer to it?
You should use stack semantics for the member and add a destructor to the containing class.
Then the member will be disposed.
See http://msdn.microsoft.com/en-us/library/ms177197.aspx
ref class B
{
public:
B() {}
~B() {}
protected:
A m_a;
};
The member is still a ref. type and is still created on the heap.
Edit:
Dispose in .net is at best unfortunate, in C# the whole deterministic behaviour is broken and you have to be really rigerous with Dispose calls to get the behaviour most c++ developers expect.
In c++/cli stack semantics make it better. If you can't use them you are back to having to explicitly call dispose which in c++/cli is represented by the destructor.
The only way to automatically chain dispose calls to members is through stack semantics if the members are normal managed pointers just like c# you'll have to chain the calls manually.
Many classes could hold the same A^ pointer, there is no way to know which one should call the destructor.
You get the warning because you have implemented the destructor which causes your class to implement IDispose. This gives you a chance to clean up in a deterministic manner.
The GC alone can only collect an object with no references and call the finalizer. This is far from deterministic. Note that relying on the finalizer to do the clean up should be a safety net only as it may be called a long time in the future if at all.
I would recommend trying to design your code to allow the above pattern.
Related
#Builder
public class X {
#Nonnull String a;
#Nonnull String b;
}
main () {
X.XBuilder builder = X.builder();
//thread 1
CompletableFuture.runAsync(()-> {
builder.a("some");
});
//thread 2
CompletableFuture.runAsync(()-> {
builder.b("thing");
});
}
Here the same object is being accessed and modified at the same time.
So will this code be thread safe?
Usecase is like wants to call multiple api's, each api results is to populate the fields of class X.
If you want to know how the stuff that Lombok generates works, you can always use the delombok tool.
With regard to thread safety of #Builder, you will see that you can in fact access a builder instance from multiple threads, but only under these constraints:
Don't call the same field setter from different threads. Otherwise you'll never know which value makes it to the builder eventually.
Make sure that all value-setting threads have terminated before you call build(). (If you want to call build() in a thread, too, make sure you create this thread after all value-setting threads have terminated.)
This is necessary because #Builder wasn't designed for concurrency (as that's not something you typically do with a builder). In particular, #Builder does not use synchronization or volatile fields, so you have to create a happens-before relation for all setter calls with the build() call.
The D multithreading model disallows implicit memory sharing, preferring message passing and immutable data. However, the compiler seems to be odd about letting a this pointer through when receiving messages:
import std.concurrency;
import std.stdio;
class Wat {
int foo;
Tid workerThread;
this(int f)
{
foo = f;
workerThread = spawn(&threadedWork);
}
// Must be static. This makes sense because otherwise
// the object (via "this") would be accessible in two threads,
// and D discourages shared memory,
// preferring messages and immutable data.
static void threadedWork()
{
// Compiler correctly complains that I can't access a non-static function
// from inside a static one.
bar(42);
while (true) {
// But this is allowed. What gives?
receive (
&bar
);
}
}
void bar(int bar)
{
if (foo == bar)
writeln("The answer");
}
}
Why is the compiler allowing me to use a non-static function inside receive? Is this a bug?
Looks like a bug. What happens is &bar gets you a pointer to the method WITHOUT this which has type as a function pointer:
pragma(msg, typeof(&Wat.bar));
void function(int bar)
std.concurrency.receive then sees that and says "oh it is a handler for int messages" and accepts it.... not realizing that it also requires a hidden this argument to be passed to it.
If you try to use it, you'll get a random result/crash if it tries to access any class members because the this pointer is not actually passed to the function, so it accesses random garbage,
So while I'd say this is a bug... I'm not sure were the bug is. std.concurrency can't tell the difference between a REAL void function(int) and this fake one since the address-of operator doesn't forward information about the hidden this pointer. I think that's the real bug.
I found the following code on MSDN:
public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;
public MyResource(IntPtr handle)
{
this.handle = handle;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
CloseHandle(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource()
//obj.dispose()
}
}
Now the confusion I have here is that, if I call obj.dispose, it disposes the objects created in the class MyResources i.e. handle, component etc. But does the obj also gets removed off the heap?? Same applies with the destructor. If I don't call dispose, the destructor will be called sometime. The code inside destructor removes the contained objects. But what about the obj?
Secondly, if I don't have a destructor defined inside the class and I dont even call dispose, does the GC never come into picture here?
IDisposable exists to remove unmanaged items from your managed objects. The runtime automatically provides a destructor, this destructor here has the sole purpose of releasing unmanaged items. As soon as your object goes out of scope or is set to null and has no more references to it will eventually be cleared by the GC.
The fundamental rule I'd recommend with with IDisposable is that at any given moment in time, for every object that implements IDisposable, there should be exactly one entity which has the clearly-defined responsibility of ensuring that it will get cleaned up (almost always by calling Dispose) before it is abandoned. Such responsibility will initially belong to whatever entity calls the IDidposable object's constructor, but that entity may hand the responsibility off to some other entity (which may hand it off again, etc.).
In general, I'd guess that most programmers would be best served if they pretended finalizers and destructors did not exist. They are generally only needed as a consequence of poorly-written code, and in most cases the effort one would have to spend writing a 100%-correct finalizer/destructor and working through all the tricky issues related to threading context, accidental resurrection, etc. could be better spent ensuring that the primary rule given above is always followed. Because of some unfortunate design decisions in the Framework and its languages, there are a few situations which can't very well be handled without finalizers/destructors, but for the most part they serve to turn code which would fail relatively quickly into code which will mostly work but may sometimes fail in ways that are almost impossible to debug.
{ using Visual Studio 2010 , Win7 }
class Base
{
public:
Base() : terminateCondition(false)
{
//spawn new thread and set entry point to newThreadFunc()
}
virtual ~Base() // edited to say it's virtual.
{
terminateCondition=true;
//wait for thread to join
}
virtual void vfunc() = 0;
static void __stdcall newThreadFunc(void *args)
{
while(!terminateCondition)
pThis->vfunc();
}
volatile bool terminateCondition;
};
class Derived : public Base
{
public:
virtual void vfunc()
{
//Do Something
}
};
Derived* dPtr=new Derived; //now assume pThis is dptr
//later somewhere
delete dPtr;
This code crashes saying pure virtual called. Moving terminateCondition=true to the destructor of Derived prevents this crash. I think i partially get why. Destruction is in reverse order of construction so d'tor of Derived is executed 1st and all functionalities of Derived are destroyed before calling upon the d'tor of Base. In the meantime if pThis->vfunc() is encountered the application would crash. It crashes saying pure virtual called. I could not understand this part. Can someone please explain?
Your Base class destructor needs to be virtual, Since it is not this code invokes Undefined Behavior.
Reference:
C++03 standard: Section 5.3.5/3:
If the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
When you call a virtual function through constructor/destructor the dynamic dispatch does not work as you expect it to.
The type of this in constructor/destructor is of the type of the class who's constructor/destructor is being executed. While you expect the dynamic dispatch to call overidden derived class method Derived::vfunc(), it ends up in a call to Base::vfunc() which does not have a definition and hence results in Undefined Behavior.
Reference:
C++03 Standard 10.4/6:
"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."
This happens because in your code vfunc can be invoked while Base::Base() isn't finished yet or Base::~Base() already started. Both of these cases will invoke undefined behavior, usually manifested as "pure virtual call" error.
Reason for it being an error is that the "virtual" mechanism doesn't kick in until after the constructor of most derived object's class started running, and the "virtual" mechanism is no longer in effect after the destructor of most derived object's class finished running. So when you make a call to a virtual function while a constructor or destructor is executing on the object, the corresponding function of the class of which the constructor or destructor is executing will be called. And if that function happens to be pure virtual, the behavior is undefined.
ISO/IEC 14882:2003, 10.4/6:
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making
a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or
destroyed) from such a constructor (or destructor) is undefined.
The QFuture class has methods such as cancel(), progressValue(), etc. These can apparently be monitored via a QFutureWatcher. However, the documentation for QtConcurrent::run() reads:
Note that the QFuture returned by
QtConcurrent::run() does not support
canceling, pausing, or progress
reporting. The QFuture returned can
only be used to query for the
running/finished status and the return
value of the function.
I have looked in vain for what method actually can create a QFuture that can be cancelled and report progress for a single long-running operation. (It looks like maybe QtConcurrent::map() and similar functions can, but I just have a single, long-running method.)
(For those familiar with .Net, something like the BackgroundWorker class.)
What options are available?
Though it's been a while since this question was posted and answered I decided to add my way of solving this problem because it is rather different from what was discussed here and I think may be useful to someone else. First, motivation of my approach is that I usually don't like to invent own APIs when framework already has some mature analogs. So the problem is: we have a nice API for controlling background computations represented by the QFuture<>, but we have no object that supports some of the operations. Well, let's do it. Looking on what's going on inside QtConcurrent::run makes things much clearer: a functor is made, wrapped into QRunnable and run in the global ThreadPool.
So I created generic interface for my "controllable tasks":
class TaskControl
{
public:
TaskControl(QFutureInterfaceBase *f) : fu(f) { }
bool shouldRun() const { return !fu->isCanceled(); }
private:
QFutureInterfaceBase *fu;
};
template <class T>
class ControllableTask
{
public:
virtual ~ControllableTask() {}
virtual T run(TaskControl& control) = 0;
};
Then, following what is made in qtconcurrentrunbase.h I made q-runnable for running this kind of tasks (this code is mostly from qtconcurrentrunbase.h, but slightly modified):
template <typename T>
class RunControllableTask : public QFutureInterface<T> , public QRunnable
{
public:
RunControllableTask(ControllableTask<T>* tsk) : task(tsk) { }
virtial ~RunControllableTask() { delete task; }
QFuture<T> start()
{
this->setRunnable(this);
this->reportStarted();
QFuture<T> future = this->future();
QThreadPool::globalInstance()->start(this, /*m_priority*/ 0);
return future;
}
void run()
{
if (this->isCanceled()) {
this->reportFinished();
return;
}
TaskControl control(this);
result = this->task->run(control);
if (!this->isCanceled()) {
this->reportResult(result);
}
this->reportFinished();
}
T result;
ControllableTask<T> *task;
};
And finally the missing runner class that will return us controllable QFututre<>s:
class TaskExecutor {
public:
template <class T>
static QFuture<T> run(ControllableTask<T>* task) {
return (new RunControllableTask<T>(task))->start();
}
};
The user should sublass ControllableTask, implement background routine which checks sometimes method shouldRun() of TaskControl instance passed to run(TaskControl&) and then use it like:
QFututre<int> futureValue = TaskExecutor::run(new SomeControllableTask(inputForThatTask));
Then she may cancel it by calling futureValue.cancel(), bearing in mind that cancellation is graceful and not immediate.
I tackled this precise problem a while ago, and made something called "Thinker-Qt"...it provides something called a QPresent and a QPresentWatcher:
http://hostilefork.com/thinker-qt/
It's still fairly alpha and I've been meaning to go back and tinker with it (and will need to do so soon). There's a slide deck and such on my site. I also documented how one would change Mandelbrot to use it.
It's open source and LGPL if you'd like to take a look and/or contribute. :)
Yan's statement is inaccurate. Using moveToThread is one way of achieving the proper behavior, but it not the only method.
The alternative is to override the run method and create your objects that are to be owned by the thread there. Next you call exec(). The QThread can have signals, but make sure the connections are all Queued. Also all calls into the Thread object should be through slots that are also connected over a Queued connection. Alternatively function calls (which will run in the callers thread of execution) can trigger signals to objects that are owned by the thread (created in the run method), again the connections need to be Queued.
One thing to note here, is that the constructor and destructor are running in the main thread of execution. Construction and cleanup need to be performed in run. Here is an example of what your run method should look like:
void MythreadDerrivedClass::run()
{
constructObjectsOnThread();
exec();
destructObjectsOnThread();
m_waitForStopped.wakeAll();
}
Here the constructObjectsOnThread will contain the code one would feel belongs in the constructor. The objects will be deallocated in destructObjectsOnThread. The actual class constructor will call the exit() method, causing the exec() to exit. Typically you will use a wait condition to sit in the destructor till the run has returned.
MythreadDerivedClass::~MythreadDerivedClass()
{
QMutexLocker locker(&m_stopMutex);
exit();
m_waitForStopped.wait(locker.mutex(), 1000);
}
So again, the constructor and destructor are running in the parent thread. The objects owned by the thread must be created in the run() method and destroyed before exiting run. The class destructor should only tell the thread to exit and use a QWaitCondition to wait for the thread to actually finish execution. Note when done this way the QThread derived class does have the Q_OBJECT macro in the header, and does contain signals and slots.
Another option, if you are open to leveraging a KDE library, is KDE's Thread Weaver. It's a more complete task based multitasking implementation similar QtConcurrentRun in that it leverages a thread pool. It should be familiar for anyone from a Qt background.
That said, if you are open to a c++11 method of doing the same thing, I would look at std::async. For one thing, you will no longer have any dependance on Qt, but the api also makes more clear what is going on. With MythreadDerivedClass class inheriting from QThread, the reader gets the impression that MythreadDerivedClass is a thread (since it has an inheritance relationship), and that all its functions run on a thread. However, only the run() method actually runs on a thread. std::async is easier to use correctly, and has fewer gotcha's. All our code is eventually maintained by someone else, and these sorta things matter in the long run.
C++11 /w QT Example:
class MyThreadManager {
Q_OBJECT
public:
void sndProgress(int percent)
void startThread();
void stopThread();
void cancel() { m_cancelled = true; }
private:
void workToDo();
std::atomic<bool> m_cancelled;
future<void> m_threadFuture;
};
MyThreadedManger::startThread() {
m_cancelled = false;
std::async(std::launch::async, std::bind(&MyThreadedManger::workToDo, this));
}
MyThreadedManger::stopThread() {
m_cancelled = true;
m_threadfuture.wait_for(std::chrono::seconds(3))); // Wait for 3s
}
MyThreadedManger::workToDo() {
while(!m_cancelled) {
... // doWork
QMetaInvoke::invokeMethod(this, SIGNAL(sndProgress(int)),
Qt::QueuedConnection, percentDone); // send progress
}
}
Basically, what I've got here isn't that different from how your code would look like with QThread, however, it is more clear that only workToDo() is running on the thread and that MyThreadManager is only managing the thread and not the thread itself. I'm also using MetaInvoke to send a queued signal for sending our progress updates with takes care of the progress reporting requirement. Using MetaInvoke is more explicit and always does the right thing (doesn't matter how you connect signals from your thread managers to other class's slots). You can see that the loop in my thread checks an atomic variable to see when the process is cancelled, so that handles the cancellation requirement.
Improve #Hatter answer to support Functor.
#include <QFutureInterfaceBase>
#include <QtConcurrent>
class CancellationToken
{
public:
CancellationToken(QFutureInterfaceBase* f = NULL) : m_f(f){ }
bool isCancellationRequested() const { return m_f != NULL && m_f->isCanceled(); }
private:
QFutureInterfaceBase* m_f;
};
/*== functor task ==*/
template <typename T, typename Functor>
class RunCancelableFunctorTask : public QtConcurrent::RunFunctionTask<T>
{
public:
RunCancelableFunctorTask(Functor func) : m_func(func) { }
void runFunctor() override
{
CancellationToken token(this);
this->result = m_func(token);
}
private:
Functor m_func;
};
template <typename Functor>
class RunCancelableFunctorTask<void, Functor> : public QtConcurrent::RunFunctionTask<void>
{
public:
RunCancelableFunctorTask(Functor func) : m_func(func) { }
void runFunctor() override
{
CancellationToken token(this);
m_func(token);
}
private:
Functor m_func;
};
template <class T>
class HasResultType
{
typedef char Yes;
typedef void *No;
template<typename U> static Yes test(int, const typename U::result_type * = 0);
template<typename U> static No test(double);
public:
enum { Value = (sizeof(test<T>(0)) == sizeof(Yes)) };
};
class CancelableTaskExecutor
{
public:
//function<T or void (const CancellationToken& token)>
template <typename Functor>
static auto run(Functor functor)
-> typename std::enable_if<!HasResultType<Functor>::Value,
QFuture<decltype(functor(std::declval<const CancellationToken&>()))>>::type
{
typedef decltype(functor(std::declval<const CancellationToken&>())) result_type;
return (new RunCancelableFunctorTask<result_type, Functor>(functor))->start();
}
};
User example:
#include <QDateTime>
#include <QDebug>
#include <QTimer>
#include <QFuture>
void testDemoTask()
{
QFuture<void> future = CancelableTaskExecutor::run([](const CancellationToken& token){
//long time task..
while(!token.isCancellationRequested())
{
qDebug() << QDateTime::currentDateTime();
QThread::msleep(100);
}
qDebug() << "cancel demo task!";
});
QTimer::singleShot(500, [=]() mutable { future.cancel(); });
}
For a long running single task, QThread is probably your best bet. It doesn't have build-in progress reporting or canceling features so you will have to roll your own. But for simple progress update it's not that hard. To cancel the task, check for a flag that can be set from calling thread in your task's loop.
One thing to note is if you override QThread::run() and put your task there, you can't emit signal from there since the QThread object is not created within the thread it runs in and you can't pull the QObject from the running thread. There is a good writeup on this issue.