view dreactor/util/ThreadSafeQueue.d @ 0:7a315154bf5e

Initial commit
author rick@minifunk
date Sun, 08 Jun 2008 01:45:38 -0400
parents
children e3dbc9208822
line wrap: on
line source

module dreactor.util.ThreadSafeQueue;

import tango.util.collection.CircularSeq;

/******************************************************************************

    ThreadSafeQueue
    Queue that is probably thread safe. It acts as a job queue, in that 
    you can push or pop off of the queue. Or you can processAll, which will
    apply a delegate to each item, then clear the list. 

******************************************************************************/
class ThreadSafeQueue(TYPE)
{
public
    this(int maxsz = 1000)
    {
        list = new CircularSeq!(TYPE);
        maxsize = maxsz;
        size = 0;
    }

    synchronized bool pop(ref TYPE t)
    {
        if (list.size())
        {
            TYPE t = list.head();
            list.removeHead();
            --size;
            return true;
        }
        else
            return false;
    }

    synchronized bool push(TYPE t)
    {
        if (list.size < maxsize)
        {
            list.append(t);
            ++size;
            return true;
        }
        else
            return false;
    }

    synchronized int size()
    {
        return size();
    }

    synchronized int processAll(int delegate(ref T value) dg)
    {
        int count = 0;
        foreach(T t; list)
        {
            if (dg(t) < 0)
                break;
            ++count;
        }
        if (count == size)
            clear_();
        else
            list.removeRange(0, count);
        return count;
    }

    synchronized void clear()
    {
        clear_();
    }

private 

    void clear_()
    {
        list.removeAll();
    }

    CircularSeq!(TYPE) list;
    int maxsize;
    int size;
}