1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
// $Id: Atomic_Op.cpp 84565 2009-02-23 08:20:39Z johnnyw $
#include "ace/Synch.h"
#include "ace/Task.h"
#include "ace/Log_Msg.h"
#include "ace/Atomic_Op.h"
#if defined(RUNNING_ON_UNSAFE_MULTIPROCESSOR)
// Listing 1 code/ch14
typedef ACE_Atomic_Op<ACE_Thread_Mutex, unsigned int> SafeUInt;
// Listing 1
// Listing 2 code/ch14
typedef ACE_Atomic_Op<ACE_Thread_Mutex, int> SafeInt;
// Listing 2
#else
typedef ACE_Atomic_Op<ACE_Null_Mutex, unsigned int> SafeUInt;
typedef ACE_Atomic_Op<ACE_Null_Mutex, int> SafeInt;
#endif /* RUNNING_ON_UNSAFE_MULTIPROCESSOR) */
static const unsigned int Q_SIZE = 2;
static const int MAX_PROD = 10;
// Listing 3 code/ch14
class Producer : public ACE_Task_Base
{
public:
Producer (int *buf, SafeUInt &in, SafeUInt &out)
: buf_(buf), in_(in), out_(out)
{ }
int svc (void)
{
SafeInt itemNo = 0;
while (1)
{
// Busy wait.
do
{ }
while (in_.value () - out_.value () == Q_SIZE);
itemNo++;
buf_[in_.value () % Q_SIZE] = itemNo.value ();
in_++;
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Produced %d\n"),
itemNo.value ()));
if (check_termination (itemNo.value ()))
break;
}
return 0;
}
int check_termination (int item)
{
return (item == MAX_PROD);
}
private:
int * buf_;
SafeUInt& in_;
SafeUInt& out_;
};
class Consumer : public ACE_Task_Base
{
public:
Consumer (int *buf, SafeUInt &in, SafeUInt& out)
: buf_(buf), in_(in), out_(out)
{ }
int svc (void)
{
while (1)
{
int item;
// Busy wait.
do
{ }
while (in_.value () - out_.value () == 0);
item = buf_[out_.value () % Q_SIZE];
out_++;
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Consumed %d\n"),
item));
if (check_termination (item))
break;
}
return 0;
}
int check_termination (int item)
{
return (item == MAX_PROD);
}
private:
int * buf_;
SafeUInt& in_;
SafeUInt& out_;
};
// Listing 3
// Listing 4 code/ch14
int ACE_TMAIN (int, ACE_TCHAR *[])
{
int shared_buf[Q_SIZE];
SafeUInt in = 0;
SafeUInt out = 0;
Producer producer (shared_buf, in, out);
Consumer consumer (shared_buf, in, out);
producer.activate();
consumer.activate();
producer.wait();
consumer.wait();
return 0;
}
// Listing 4
|