Merge pull request #2309 from mitza-oci/warnings
[ACE_TAO.git] / ACE / examples / APG / ThreadSafety / RW_Lock.cpp
blob42cd9e629c03a942723d4ec63782c56ffa1ce695
1 #include "ace/config-lite.h"
2 #if defined (ACE_HAS_THREADS)
4 #include "ace/Synch.h"
5 #include "ace/Containers.h"
6 #include "ace/Task.h"
8 class Device
10 public:
11 Device (int id) : id_(id)
12 { }
14 int id_;
17 typedef ACE_DLList<Device> DeviceList;
18 typedef ACE_DLList_Iterator<Device> DeviceListIterator;
20 // Listing 1 code/ch14
21 class HA_DiscoveryAgent
23 public:
24 void add_device (Device *device)
26 ACE_WRITE_GUARD (ACE_RW_Thread_Mutex, mon, rwmutex_);
27 list_add_item_i (device);
30 void remove_device (Device *device)
32 ACE_READ_GUARD (ACE_RW_Thread_Mutex, mon, rwmutex_);
33 list_remove_item_i(device);
36 int contains_device (Device *device)
38 ACE_READ_GUARD_RETURN
39 (ACE_RW_Thread_Mutex, mon, rwmutex_, -1);
40 return list_contains_item_i (device);
43 private:
44 void list_add_item_i (Device * device);
45 int list_contains_item_i (Device * device);
46 void list_remove_item_i (Device* device);
48 private:
49 DeviceList deviceList_;
50 ACE_RW_Thread_Mutex rwmutex_;
52 // Listing 1
54 void
55 HA_DiscoveryAgent::list_add_item_i (Device *device)
57 deviceList_.insert_tail (device);
60 int
61 HA_DiscoveryAgent::list_contains_item_i (Device *device)
63 DeviceListIterator iter (deviceList_);
64 while (!iter.done ())
66 if (iter.next () == device)
67 return 1;
68 iter++;
71 return 0;
74 void
75 HA_DiscoveryAgent::list_remove_item_i (Device *device)
77 DeviceListIterator iter (deviceList_);
78 while (!iter.done ())
80 if (iter.next () == device)
82 iter.remove ();
83 break;
85 iter++;
89 static Device *devices[100];
91 class Runner : public ACE_Task_Base
93 public:
94 Runner(HA_DiscoveryAgent &agent) : agent_(agent)
95 { }
97 virtual int svc ()
99 ACE_ASSERT(agent_.contains_device(devices[9]) == 1);
100 agent_.remove_device (devices[9]);
101 ACE_ASSERT(agent_.contains_device(devices[9]) == 0);
102 return 0;
105 private:
106 HA_DiscoveryAgent &agent_;
109 int ACE_TMAIN (int, ACE_TCHAR *[])
111 HA_DiscoveryAgent agent;
113 for (int i = 0; i < 100; i++)
115 devices[i] = new Device (i);
116 agent.add_device (devices[i]);
119 Runner runner (agent);
120 runner.activate ();
122 runner.wait ();
124 return 0;
127 #else
128 #include "ace/OS_main.h"
129 #include "ace/OS_NS_stdio.h"
131 int ACE_TMAIN (int, ACE_TCHAR *[])
133 ACE_OS::puts (ACE_TEXT ("This example requires threads."));
134 return 0;
137 #endif /* ACE_HAS_THREADS */