#include <JTC\JTC.h>
#include <iostream.h>
#include <time.h>


class Bacchetta : public JTCMonitor
{
	bool occupata;
public:
	Bacchetta()
	{
		occupata = false;
	}
	void prendiBacchetta()
	{
		JTCSynchronized sync(*this);
		while( occupata )
			this->wait();
		bacchette[2]->prendiBacchetta();
		occupata = true;
	}
	void lasciaBacchetta()
	{
		JTCSynchronized sync(*this);
		occupata = false;
		   this->notify();
	}
};

Bacchetta* bacchette[5];

class Filosofo : public JTCThread
{
	int numFilosofo;
public:
	Filosofo(int i)
	{
		numFilosofo = i;
	}
	virtual void run()
	{
        srand(numFilosofo * time(0) );
		while(true)
		{
			cout << "Il filosofo " << numFilosofo << " dorme." << endl;
			sleep(rand() % 1000);
			cout << "Il filosofo " << numFilosofo << " si sveglia." << endl;
			bacchette[numFilosofo]->prendiBacchetta();
			sleep(rand() % 500);
			bacchette[(numFilosofo + 1) % 5]->prendiBacchetta( );
			cout << "Il filosofo " << numFilosofo << " mangia." << endl;
			sleep(rand() % 500 );
			cout << "Il filosofo " << numFilosofo << " ha finito di mangiare." << endl;
			bacchette[numFilosofo]->lasciaBacchetta();
			bacchette[(numFilosofo + 1) % 5]->lasciaBacchetta();
		}
		}
};

int main()
{
   JTCInitialize init;
   Filosofo* filosofi[5];
   for (int i = 0; i < 5; i++)
   {
	   bacchette[i] = new Bacchetta();
   }
   for (int i = 0; i < 5; i++)
   {
	   filosofi[i] = new Filosofo(i);
	   filosofi[i]->start();
   }
   return 0;
}



