/* bound.c */

# include <stdio.h>
# include <pthread.h>
# include <semaphore.h>
# include "xx.h"

void DrawArrow(int px, int py)
{
  int x1=15, y1=10, x2=20, y2=20, x3=10, y3=30;
  int x4=0,x5=5;
  _XDrawLine( px+x5, py,    px+x1, py );
  _XDrawLine( px+x1, py,    px+x1, py+y2 );
  _XDrawLine( px+x1, py+y2, px+x2, py+y2 );
  _XDrawLine( px+x2, py+y2, px+x3, py+y3 );
  _XDrawLine( px+x3, py+y3, px+x4, py+y2 );
  _XDrawLine( px+x4, py+y2, px+x5, py+y2 );
  _XDrawLine( px+x5, py+y2, px+x5, py    );
}

void DrawSquare(int px, int py)
{
  int yy=0;
  py-=200;
  _XDrawLine( px,    py+yy, px+15, py+yy );
  _XDrawLine( px+15, py+yy, px+15, py+15+yy );
  _XDrawLine( px+15, py+15+yy, px, py+15+yy );
  _XDrawLine( px,    py+15+yy, px, py+yy );
  _XDrawLine( px,    py+yy, px+15, py+15+yy );
  _XDrawLine( px+15, py+yy, px, py+15+yy );
}

void DeleteInputArrow(int p)
{
  int ip=20*(p%20);
  _XSetBlack; DrawArrow( 50+ip, 40 );
  _XFlush;
}

void DrawInputArrow(int p)
{
  int ip=20*(p%20);
  _XSetYellow; DrawArrow( 50+ip, 40 ); DrawSquare( 52+ip, 330 );
  _XFlush;
}

void DeleteOutputArrow(int p)
{
  int ip=20*(p%20);
  _XSetBlack; DrawArrow( 50+ip, 200 );
  _XFlush;
}

void DrawOutputArrow(int p)
{
  int ip=20*(p%20);
  _XSetYellow; DrawArrow( 50+ip, 200 );
  _XSetBlack; DrawSquare( 52+ip, 330 );
  _XFlush;
}

void DrawServant()
{
  int i;
  int x1=50, y1=80, x2=450, y2=180;
  _XSetYellow;
  _XDrawLine( x1, y1, x2, y1 ); _XDrawLine( x2, y1, x2, y2 );
  _XDrawLine( x2, y2, x1, y2 ); _XDrawLine( x1, y2, x1, y1 );
  for(i=1;i<20;i++) _XDrawLine( x1+20*i, y1, x1+20*i, y2 );
}

void producer(sem_t arg[]); 
/*void producer();*/
void consumer(sem_t arg[]); 
/*void consumer();*/

void producer(sem_t arg[])
{
  int i, j=0;
  for(i=0;i<100000;) {
    sem_wait(&arg[0]);
    usleep(100000);
    DeleteInputArrow(j++);
    DrawInputArrow(j);
    sem_post(&arg[1]);
  }
}

void consumer(sem_t arg[])
{
  int j;
  for(j=0;j<100000;) {
    sem_wait(&arg[1]);
    usleep(150000);
    DeleteOutputArrow(j++);
    DrawOutputArrow(j);
    sem_post(&arg[0]);
  }
}

int main(void)
{
    pthread_t prod, cons;
    sem_t sem0,sem1;
    sem_t buf[2];
    sem_init(&sem0,(int)0,(unsigned int)10);
    sem_init(&sem1,(int)0,(unsigned int)0);
    buf[0] = sem0; buf[1]=sem1;
    _XOpen3;
    DrawServant();
    pthread_create(&prod,NULL,(void*)producer,(void*)buf);
    pthread_create(&cons,NULL,(void*)consumer,(void*)buf);
    pthread_join(prod,NULL);
    pthread_join(cons,NULL);
    while(1) {
        usleep(100000);
	_XFlush;
    }
    _XClose;
}

/* End of file bound0.c -------- */









