ice 多线程同步范例

#include
#include
#include
#include
using namespace std;
template class Queue: public IceUtil::Monitor
{
public:
    Queue() : _waitingReaders(0) {}
void put(const T & item)
{
    IceUtil::Monitor::Lock lock(*this);
    _q.push_back(item);
    if (_waitingReaders)  notify();
}
T get()
 {
    IceUtil::Monitor::Lock lock(*this);
    while (_q.size() == 0)
 {
    try
  {
   ++_waitingReaders;
   wait();
   --_waitingReaders;
  } catch (...)
  {
    --_waitingReaders;
   throw;
  }
 }
    T item = _q.front();
    _q.pop_front();
    return item;
}
private:
 list _q;
 short _waitingReaders;
};


Queue q;

class ReaderThread : public IceUtil::Thread
{
 virtual void run()
 {
  for (int i = 0; i < 100; ++i)cout << q.get() << endl;
 }
};
class WriterThread : public IceUtil::Thread
{
 virtual void run()
 {
  for (int i = 0; i < 100; ++i) q.put(i);
 }
};
void main()
{
 vector threads;
 int i;
 // Create five reader threads and start them
 //
 for (i = 0; i < 5; ++i)
 {
  IceUtil::ThreadPtr t = new ReaderThread;
  threads.push_back(t->start());
 }

 // Create five writer threads and start them
 //
 for (i = 0; i < 5; ++i)
 {
  IceUtil::ThreadPtr t = new WriterThread;
  threads.push_back(t->start());
 }
 // Wait for all threads to finish
 //
 for (vector::iterator p= threads.begin(); p!= threads.end(); ++p)
 {
  p->join();
 }
}

你可能感兴趣的:(ice 多线程同步范例)