Merge branch 'master' into jwi-bcc64xsingletonwarning
[ACE_TAO.git] / ACE / examples / Smart_Pointers / Widget_Part_Impl.cpp
blobbc55b76be7f51d276eee8979f3abf53d7dc1db85
1 /* -*- C++ -*- */
2 //=============================================================================
3 /**
4 * @file Widget_Part_Impl.cpp
6 * @author Christopher Kohlhoff <chris@kohlhoff.com>
7 */
8 //=============================================================================
10 #include "Widget_Part_Impl.h"
11 #include "ace/ACE.h"
12 #include "ace/Log_Msg.h"
13 #include "ace/Refcounted_Auto_Ptr.h"
14 #include "ace/Unbounded_Queue.h"
15 #include "ace/Null_Mutex.h"
17 Widget_Part_Impl::Widget_Part_Impl (Widget *owner, const char* name, int size)
18 : owner_ (owner),
19 name_ (ACE::strnew (name)),
20 size_ (size)
22 ACE_DEBUG ((LM_DEBUG, "Widget_Part_Impl constructor\n"));
25 Widget_Part_Impl::~Widget_Part_Impl ()
27 ACE_DEBUG ((LM_DEBUG, "Widget_Part_Impl destructor\n"));
29 delete [] name_;
32 void Widget_Part_Impl::print_info ()
34 ACE_DEBUG ((LM_INFO, "Widget part: name=%s size=%d\n", name_, size_));
37 void Widget_Part_Impl::remove_from_owner ()
39 // Since we only have a raw pointer to refer to the owner, we have no way of
40 // checking whether the owner still exists, and if it does guaranteeing that
41 // it will continue to exist for the duration of this call. This is not an
42 // issue in this limited example program, but in multithreaded applications
43 // this function may be called from a different thread to that managing the
44 // lifetime of the owner object. See the Gadget example for how
45 // ACE_Strong_Bound_Ptr/ACE_Weak_Bound_Ptr can be used to address the problem.
47 // Take all existing parts from the owner and build up a temporary queue. If
48 // we find ourselves then we won't add ourselves to the queue. We will
49 // actually store ACE_Refcounted_Auto_Ptr instances in the queue, and since we
50 // know that there is only one thread involved we can use ACE_Null_Mutex to
51 // eliminate the locking overhead.
52 ACE_Unbounded_Queue<ACE_Refcounted_Auto_Ptr<Widget_Part, ACE_Null_Mutex> > parts;
53 for (;;)
55 ACE_Refcounted_Auto_Ptr<Widget_Part, ACE_Null_Mutex> part (owner_->remove_part ());
56 if (part.null ())
57 break;
58 if (part.get () == this)
59 // Someone else will be responsible for our lifetime.
60 part.release();
61 else
62 parts.enqueue_tail (part);
65 // Add the remaining parts back to the gadget.
66 while (!parts.is_empty ())
68 ACE_Refcounted_Auto_Ptr<Widget_Part, ACE_Null_Mutex> part;
69 parts.dequeue_head (part);
70 owner_->add_part (part.release ());