Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / APG / Threads / Guards.cpp
blob31c0498db152839a808ac92ea9ddad540defb710
1 #include "ace/config-lite.h"
2 #if defined (ACE_HAS_THREADS)
4 #include "ace/OS_main.h"
5 #include "ace/OS_Memory.h"
6 #include "ace/Guard_T.h"
7 #include "ace/Log_Msg.h"
8 #include "ace/Thread_Mutex.h"
10 // This file exists primarily to get code into the book to show different
11 // ways to do the same thing. For complete context and explanation, please
12 // see APG chapter 12.
14 class HA_Device_Repository {
15 public:
16 int update_device (int device_id);
18 private:
19 ACE_Thread_Mutex mutex_;
22 class Object {
24 static Object *object;
26 #if 0
27 // This is less-desired way to do this...
29 // Listing 1 code/ch12
30 int
31 HA_Device_Repository::update_device (int device_id)
33 this->mutex_.acquire ();
34 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Updating device %d\n"),
35 device_id));
37 // Allocate a new object.
38 ACE_NEW_RETURN (object, Object, -1);
39 // ...
40 // Use the object
42 this->mutex_.release ();
44 // Listing 1
45 // Listing 2 code/ch12
46 int
47 HA_Device_Repository::update_device (int device_id)
49 // Construct a guard specifying the type of the mutex as
50 // a template parameter and passing in the mutex to hold
51 // as a parameter.
52 // FUZZ: disable check_for_ACE_Guard
53 ACE_Guard<ACE_Thread_Mutex> guard (this->mutex_);
54 // FUZZ: enable check_for_ACE_Guard
56 // This can throw an exception that is not caught here.
57 ACE_NEW_RETURN (object, Object, -1);
58 // ..
59 // Use the object.
60 // ..
61 // Guard is destroyed, automatically releasing the lock.
63 // Listing 2
64 #endif /* 0 */
66 // Listing 3 code/ch12
67 int
68 HA_Device_Repository::update_device (int /* device_id */)
70 ACE_GUARD_RETURN (ACE_Thread_Mutex, mon, mutex_, -1);
72 ACE_NEW_RETURN (object, Object, -1);
73 // Use the object.
74 // ...
75 return 0;
77 // Listing 3
79 int ACE_TMAIN (int, ACE_TCHAR *[])
81 HA_Device_Repository rep;
82 rep.update_device (42);
83 return 0;
86 #else
87 #include "ace/OS_main.h"
88 #include "ace/OS_NS_stdio.h"
90 int ACE_TMAIN (int, ACE_TCHAR *[])
92 ACE_OS::puts (ACE_TEXT ("This example requires threads."));
93 return 0;
96 #endif /* ACE_HAS_THREADS */