octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Thread-safety issues in QtHandles


From: Michael Goffioul
Subject: Re: Thread-safety issues in QtHandles
Date: Mon, 31 Oct 2011 09:38:58 +0000

On Mon, Oct 31, 2011 at 9:29 AM, Michael Goffioul
<address@hidden> wrote:
>> Right, the idea there is to increment the count so that the object
>> that is being wrapped won't be deleted early.  Maybe that is not an
>> issue with a shared_ptr?  I don't know, as I don't understand
>> precisely how it is supposed to work in place of reference counting.
>
> shared_ptr class actually does internal reference counting, but it
> does it in a thread-safe way (using CPU-atomic operations and volatile
> variables). But then the problem is that the referenced class does not
> have any knowledge of the reference count, which is handled one level
> up, in the shared_ptr class. At the moment, I'm investigating a way to
> solve the problem, using enable_shared_from_this class or weak_ptr
> class.

I think I found a way to solve the problem, which basically boils down
to (re)creating a shared_ptr from this without messing up reference
counting of possibly other shared_ptr objects pointing to "this". This
is illustrated in the following example:


#ifdef _MSC_VER
#include <memory>
#else
#include <tr1/memory>
#endif
#include <stdio.h>

class A : public std::tr1::enable_shared_from_this<A>
{
public:
        A (void) { }
        A (const A& a) { }
        virtual ~A (void) { }
};

int main (int argc, char **argv)
{
        A* a = new A ();

        std::tr1::shared_ptr<A> p1 (a);
        std::tr1::shared_ptr<A> p2 = a->shared_from_this ();

        printf ("p1:count = %d\n", p1.use_count ());
        printf ("p2:count = %d\n", p2.use_count ());

        return 0;
}

The downside is the additional memory used (I think every object has a
weak_ptr to itself).

Michael.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]