#ifndef QUEUE_H
#define QUEUE_H

/*
 * @(#)Queue.h
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 1999-2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 */

#include <pthread.h>
#include <unistd.h>

/**
 * Implementation of a queue to reserve resources.
 *
 * @version 20021101
 * @author Jörg P. M. Haeger
 */
class Queue {
	pthread_mutex_t mutex;
	int *items;
	int n, maxItemsNum;
public:
	Queue(int maxItemsNum) {
		pthread_mutex_init(&mutex, NULL);
		items = new int[maxItemsNum];
		n = 0;
		this->maxItemsNum = maxItemsNum;
	}

	void add(int ID) {
		pthread_mutex_lock(&mutex);
		if (n == maxItemsNum) {
			pthread_mutex_unlock(&mutex);
			throw new Exception("too many users at the same time");
		}
		items[n++] = ID;
		pthread_mutex_unlock(&mutex);
	}

	int getRank(int ID) {
		pthread_mutex_lock(&mutex);
		int i;
		for (i = 0; i < n && items[i] != ID; i++);
		pthread_mutex_unlock(&mutex);
		return i;
	}

	void remove(int ID) {
		pthread_mutex_lock(&mutex);
		int i;
		for (i = 0; i < n && items[i] != ID; i++);
		for (; i < n - 1; i++)
			items[i] = items[i + 1];
		n--;
		pthread_mutex_unlock(&mutex);
	}
};

#endif
