首先简单看下这个类的使用,使用很简单,就是定义了一种增减操作为原子操作的类型。下面是实例代码,为ACE6.0自带的examples里面的代码,实现了生产者消费者这个经典的模型。
#include "ace/Synch.h"
#include "ace/Task.h"
#include "ace/Log_Msg.h"
#include "ace/Atomic_Op.h"
#if defined(RUNNING_ON_UNSAFE_MULTIPROCESSOR)
typedef ACE_Atomic_Op<ACE_Thread_Mutex, unsigned int> SafeUInt;
typedef ACE_Atomic_Op<ACE_Thread_Mutex, int> SafeInt;
#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;
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)
{ }