Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / APG / Threads / Condition_Variables.cpp
blobdea1e77d04e3a37ce84f737bc5feab65414a9274
1 #include "ace/config-lite.h"
2 #if defined (ACE_HAS_THREADS)
4 #include "ace/Task.h"
5 #include "ace/Synch.h"
6 #include "ace/Condition_T.h"
8 // Listing 1 code/ch12
9 class HA_Device_Repository
11 public:
12 HA_Device_Repository() : owner_(0)
13 { }
15 int is_free ()
16 { return (this->owner_ == 0); }
18 int is_owner (ACE_Task_Base* tb)
19 { return (this->owner_ == tb); }
21 ACE_Task_Base *get_owner ()
22 { return this->owner_; }
24 void set_owner (ACE_Task_Base *owner)
25 { this->owner_ = owner; }
27 int update_device (int device_id);
29 private:
30 ACE_Task_Base * owner_;
32 // Listing 1
34 class HA_CommandHandler : public ACE_Task_Base
36 public:
37 enum {NUM_USES = 10};
39 HA_CommandHandler (HA_Device_Repository& rep,
40 ACE_Condition<ACE_Thread_Mutex> &wait,
41 ACE_Thread_Mutex& mutex)
42 : rep_(rep), waitCond_(wait), mutex_(mutex)
43 { }
45 virtual int svc ();
47 private:
48 HA_Device_Repository &rep_;
49 ACE_Condition<ACE_Thread_Mutex> &waitCond_;
50 ACE_Thread_Mutex &mutex_;
52 // Listing 2 code/ch12
53 int
54 HA_CommandHandler::svc ()
56 ACE_DEBUG ((LM_DEBUG,
57 ACE_TEXT ("(%t) Handler Thread running\n")));
59 for (int i = 0; i < NUM_USES; i++)
61 this->mutex_.acquire ();
62 while (!this->rep_.is_free ())
63 this->waitCond_.wait ();
64 this->rep_.set_owner (this);
65 this->mutex_.release ();
67 this->rep_.update_device (i);
69 ACE_ASSERT (this->rep_.is_owner (this));
70 this->rep_.set_owner (0);
72 this->waitCond_.signal ();
75 return 0;
77 // Listing 2
78 int
79 HA_Device_Repository::update_device (int device_id)
81 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Updating device %d\n"),
82 device_id));
84 ACE_OS::sleep (1);
85 return 0;
87 // Listing 3 code/ch12
88 int ACE_TMAIN (int, ACE_TCHAR *[])
90 HA_Device_Repository rep;
91 ACE_Thread_Mutex rep_mutex;
93 //FUZZ: disable check_for_lack_ACE_OS
94 ACE_Condition<ACE_Thread_Mutex> wait (rep_mutex);
95 //FUZZ: enable check_for_lack_ACE_OS
97 HA_CommandHandler handler1 (rep, wait, rep_mutex);
98 HA_CommandHandler handler2 (rep, wait, rep_mutex);
100 handler1.activate ();
101 handler2.activate ();
103 handler1.wait ();
104 handler2.wait ();
106 return 0;
108 // Listing 3
110 #else
111 #include "ace/OS_main.h"
112 #include "ace/OS_NS_stdio.h"
114 int ACE_TMAIN (int, ACE_TCHAR *[])
116 ACE_OS::puts (ACE_TEXT ("This example requires threads."));
117 return 0;
120 #endif /* ACE_HAS_THREADS */