Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / APG / ThreadSafety / Atomic_Op.cpp
blobdf3eea5c359b1bd22219d07e202a378e4cd6478a
1 #include "ace/Synch.h"
2 #include "ace/Task.h"
3 #include "ace/Log_Msg.h"
4 #include "ace/Atomic_Op.h"
6 #if defined(RUNNING_ON_UNSAFE_MULTIPROCESSOR)
7 // Listing 1 code/ch14
8 typedef ACE_Atomic_Op<ACE_Thread_Mutex, unsigned int> SafeUInt;
9 // Listing 1
10 // Listing 2 code/ch14
11 typedef ACE_Atomic_Op<ACE_Thread_Mutex, int> SafeInt;
12 // Listing 2
13 #else
14 typedef ACE_Atomic_Op<ACE_Null_Mutex, unsigned int> SafeUInt;
15 typedef ACE_Atomic_Op<ACE_Null_Mutex, int> SafeInt;
16 #endif /* RUNNING_ON_UNSAFE_MULTIPROCESSOR) */
18 static const unsigned int Q_SIZE = 2;
19 static const int MAX_PROD = 10;
21 // Listing 3 code/ch14
22 class Producer : public ACE_Task_Base
24 public:
25 Producer (int *buf, SafeUInt &in, SafeUInt &out)
26 : buf_(buf), in_(in), out_(out)
27 { }
29 int svc ()
31 SafeInt itemNo = 0;
32 while (1)
34 // Busy wait.
36 { }
37 while (in_.value () - out_.value () == Q_SIZE);
39 itemNo++;
40 buf_[in_.value () % Q_SIZE] = itemNo.value ();
41 in_++;
43 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Produced %d\n"),
44 itemNo.value ()));
46 if (check_termination (itemNo.value ()))
47 break;
50 return 0;
53 int check_termination (int item)
55 return (item == MAX_PROD);
58 private:
59 int * buf_;
60 SafeUInt& in_;
61 SafeUInt& out_;
64 class Consumer : public ACE_Task_Base
66 public:
67 Consumer (int *buf, SafeUInt &in, SafeUInt& out)
68 : buf_(buf), in_(in), out_(out)
69 { }
71 int svc ()
73 while (1)
75 int item;
77 // Busy wait.
79 { }
80 while (in_.value () - out_.value () == 0);
82 item = buf_[out_.value () % Q_SIZE];
83 out_++;
85 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Consumed %d\n"),
86 item));
88 if (check_termination (item))
89 break;
92 return 0;
95 int check_termination (int item)
97 return (item == MAX_PROD);
100 private:
101 int * buf_;
102 SafeUInt& in_;
103 SafeUInt& out_;
105 // Listing 3
107 // Listing 4 code/ch14
108 int ACE_TMAIN (int, ACE_TCHAR *[])
110 int shared_buf[Q_SIZE];
111 SafeUInt in = 0;
112 SafeUInt out = 0;
114 Producer producer (shared_buf, in, out);
115 Consumer consumer (shared_buf, in, out);
117 producer.activate();
118 consumer.activate();
119 producer.wait();
120 consumer.wait();
122 return 0;
124 // Listing 4